41 lines
1.2 KiB
Plaintext
41 lines
1.2 KiB
Plaintext
|
|
var limitConnect = 0;
|
|||
|
|
init();
|
|||
|
|
function init() {
|
|||
|
|
var ws = new WebSocket(webSocketUrl);
|
|||
|
|
// 获取连接状态
|
|||
|
|
console.log('ws连接状态:' + ws.readyState);
|
|||
|
|
//监听是否连接成功
|
|||
|
|
ws.onopen = function () {
|
|||
|
|
console.log('ws连接状态:' + ws.readyState);
|
|||
|
|
limitConnect = 0;
|
|||
|
|
//连接成功则发送一个数据
|
|||
|
|
ws.send('我们建立连接啦');
|
|||
|
|
}
|
|||
|
|
// 接听服务器发回的信息并处理展示
|
|||
|
|
ws.onmessage = function (data) {
|
|||
|
|
console.log('接收到来自服务器的消息:');
|
|||
|
|
console.log(data);
|
|||
|
|
let content = JSON.parse(data.data).noticeType;
|
|||
|
|
remindInfo(content);
|
|||
|
|
//完成通信后关闭WebSocket连接
|
|||
|
|
// ws.close();
|
|||
|
|
}
|
|||
|
|
// 监听连接关闭事件
|
|||
|
|
ws.onclose = function () {
|
|||
|
|
// 监听整个过程中websocket的状态
|
|||
|
|
console.log('ws连接状态:' + ws.readyState);
|
|||
|
|
reconnect();
|
|||
|
|
|
|||
|
|
}
|
|||
|
|
// 监听并处理error事件
|
|||
|
|
ws.onerror = function (error) {
|
|||
|
|
console.log(error);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
function reconnect() {
|
|||
|
|
limitConnect++;
|
|||
|
|
console.log("重连第" + limitConnect + "次");
|
|||
|
|
setTimeout(function () {
|
|||
|
|
init();
|
|||
|
|
}, 2000);
|
|||
|
|
}
|