var socket = {
initWebSocket() {
this.connection();
let that= this;
// 断开重连机制,尝试发送消息,捕获异常发生时重连
this.timer = setInterval(() => {
try {
that.stompClient.send("test");
} catch (err) {
console.log("断线了: " + err);
that.connection();
}
}, 5000);
this.sendName();
},
connection() {
let headers = {
token:store.getters.token,
username: window.localStorage.getItem('faceUserName')
};
// 建立连接对象
let socket = new SockJS('http://localhost:8080/bullet?token=' + headers.token + '&username=' + headers.username);
// 获取STOMP子协议的客户端对象
this.stompClient = Stomp.over(socket);
// 向服务器发起websocket连接
this.stompClient.connect(headers,() => {
this.stompClient.subscribe('/topic/getResponse', (response) => { // 订阅服务端提供的某个topic
console.log("topic/getResponse", response)
this.showResponse(response);
});
}, (err) => {
// 连接发生错误时的处理函数
// console.log('失败')
console.log("订阅失败",err);
});
},
disconnect() {
if (this.stompClient) {
this.stompClient.disconnect();
}
},
showResponse(message){
console.log(message);
},
sendName() {
let that = this;
setInterval(function () {
try{
that.stompClient.send("/app/chat", {}, JSON.stringify({'username': "tom", 'message':'hello xiaoming'}));//5
}catch (e) {
console.log(e)
}
}, 5000)
}
}
转载于:https://my.oschina.net/moyesen/blog/3071843
该博客展示了一段JavaScript代码,用于实现WebSocket连接。代码包含初始化WebSocket、建立连接、断开连接、显示响应和发送消息等功能,还设置了断开重连机制,通过定时发送消息捕获异常来触发重连,同时订阅服务端的topic接收响应。

2751

被折叠的 条评论
为什么被折叠?



