用websocket建立遠端連線(vue)
阿新 • • 發佈:2018-11-22
一。用引入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() {
// 建立連線物件
this
.socket =
new
SockJS(
'http://xxxxxx:8089/ws'
);//連線服務端提供的通訊介面,連線以後才可以訂閱廣播訊息和個人訊息
// 獲取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"
);
}
}
}
};