后端地址是http的 websocket地址 ws开头;后端地址是https的,websocket地址wss开头;
对于websocket没有跨域的问题
import { MessageBox } from 'element-ui';
let url = "ws://192.168.0.181:8000"; //请求的后端地址
let websocket = null;//全局WebSocket对象
let lockReconnect = false; // 网络断开重连
let wsCreateHandler = null; // 创建连接
export function createWebSocket(fn){
try{
if ('WebSocket' in window) {
websocket = new WebSocket(`${url}/webSocketServer?token=${getToken()}`);
} else if ('MozWebSocket' in window) {
websocket = new MozWebSocket(`${url}/webSocketServer?token=${getToken()}`);
} else {
websocket = new SockJS(`${url}/sockjs/webSocketServer?token=${getToken()}`);
}
}catch {
reconnect();
return;
}
websocket.onopen = function(event) {
// websocket.send("连接成功");
console.log("服务已连接")
};
websocket.onmessage = function(event){
var data=JSON.parse(event.data);
if(data.type === 'exit'){
MessageBox.alert(data.name, '提示', {
dangerouslyUseHTMLString: true,
showConfirmButton: true,
type: 'warning',
}).then(()=>{
store.dispatch('user/resetToken').then(() => {
removeToken();
// window.location.reload();
router.replace("/login")
});
});
}
fn(data);
};
websocket.onclose = function(event) {
console.log("服务连接关闭")
};
websocket.onerror = function(event) {
console.log(event,"连接出错")
};
}
/**
* 异常处理
* 处理可以检测到的异常,并尝试重新连接
*/
function reconnect() {
if (lockReconnect) {
return;
}
console.log("reconnect");
lockReconnect = true;
// 没链接上会一直连接,设置延迟,避免过多请求
wsCreateHandler && clearTimeout(wsCreateHandler);
wsCreateHandler = setTimeout(function() {
console.log("-----websoket异常-------");
createWebSocket();
lockReconnect = false;
}, 1000);
}
export function websocketClose() {
console.log('执行了关闭')
websocket.close(); //手动关闭websocket
}
文章来源:https://www.toymoban.com/news/detail-505296.html
注意:系统退出后需要关闭websocket,尤其是平台需要单账号登陆的。文章来源地址https://www.toymoban.com/news/detail-505296.html
到了这里,关于js中使用websocket的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!