一。用引入js方式
1 在main.js中引入
//引入websocket
import '@/assets/js/sockjs.min.js';
import '@/assets/js/stomp.min.js';
2 在代碼里書寫
//與服務器建立==>監聽是否被掃
scanConnect(){
this.refreshConnect();
var socket = new SockJS('http://118.178.118.114/zjzwfw-zwmp-api/endpoint-websocket');
this.stompClient = Stomp.over(socket);
var _self=this;
_self.stompClient.connect({'token':sessionStorage.getItem('token')}, function (frame) {
console.log(11, _self.stompClient);
});
});
},
//取消與服務器端的鏈接
disconnect(){
if (this.stompClient != null) {
this.stompClient.disconnect();
console.log("Disconnected",this.stompClient);
}
},
二。用npm構建
// 安裝命令行: npm install sockjs-client 和npm install @stomp/stompjs
// 安裝並引入相關模塊
import SockJS from
'sockjs-client'
;
import Stomp from
'stompjs'
;
export
default
{
data() {
return
{
dataList: []
};
},
mounted:
function
(){
this
.initWebSocket();
},
beforeDestroy:
function
() {
// 頁面離開時斷開連接,清除定時器
this
.disconnect();
clearInterval(
this
.timer);
},
methods: {
initWebSocket() {
this
.connection();
let self =
this
;
// 斷開重連機制,嘗試發送消息,捕獲異常發生時重連
this
.timer = setInterval(() => {
try
{
self.stompClient.send(
"test"
);
}
catch
(err) {
console.log(
"斷線了: "
+ err);
self.connection();
}
}, 5000);
},
removeTab(targetName) {
console.log(targetName)
},
connection() {
// 建立連接對象
// 獲取STOMP子協議的客戶端對象
this
.stompClient = Stomp.over(
this
.socket);
// 定義客戶端的認證信息,按需求配置
var
headers = {
login:
'mylogin'
,
passcode:
'mypasscode'
,
// additional header
'client-id'
:
'my-client-id'
};
// 向服務器發起websocket連接
this
.stompClient.connect(headers,(frame) => {
this
.stompClient.subscribe(
'/topic/chat_msg'
, (msg) => {
// 訂閱服務端提供的某個topic
consolel.log(msg.body);
// msg.body存放的是服務端發送給我們的信息
});
}, (err) => {
});
},
disconnect() {
if
(
this
.stompClient !=
null
) {
this
.stompClient.disconnect();
console.log(
"Disconnected"
);
}
}
}
};