プロジェクトで作業するときは、シングルトン モードで WebSocket を使用するのが快適なので、お勧めします。
プロジェクトは vue3+antdv を使用するため、プロンプトは ant-design-vue のコンポーネントを使用します。
import store from '@/store';
import notification from 'ant-design-vue/es/notification';
// import { getToken } from '@/utils/auth';
// import { ACCESS_TOKEN } from '@/store/mutation-types';
// 使用单例模式,创建WebSocket唯一实例
export default (function getWebSocket() {
let $wsInstance = null;
class MyWebSocket {
constructor(url, initMessage) {
this.url = url;
this.start(initMessage);
}
start(initMessage) {
if ('WebSocket' in window) {
// 打开一个 web socket
this.ws = new WebSocket(this.url);
console.log(this.ws);
this.ws.onopen = () => {
if (initMessage) {
this.sendMessage(initMessage);
}
};
this.ws.onmessage = (mes) => {
console.log(mes);
};
this.ws.onclose = () => {
$wsInstance = null; // 销毁websockket实例
};
this.ws.onerror = () => {
this.ws.close();
$wsInstance = null; // 销毁websockket实例
notification.error({
message: '提示',
description: '消息推送错误,请刷新浏览器重试!',
});
};
} else {
// 浏览器不支持 WebSocket
notification.error({
message: '提示',
description: '您的浏览器不支持 WebSocket!',
});
}
}
sendMessage(message) {
if ($wsInstance) {
this.ws.send(message);
console.log($wsInstance);
} else {
notification.error({
message: '提示',
description: '消息推送错误,请刷新浏览器重试!',
});
}
}
getWS() {
return this.ws;
}
}
// 返回的方法
return function getWS(initMessage) {
if (!$wsInstance) {
const proto = window.location.protocol === 'http:' ? 'ws:' : 'wss:';
const { userId } = store.state.user;
const wsUrl = `${proto}//${window.location.host}/common/${userId}`;
$wsInstance = new MyWebSocket(wsUrl, initMessage);
} else {
$wsInstance.sendMessage(initMessage);
}
return $wsInstance;
};
}());
次のように使用する場合:
//引入
import getWebSocket from '@/webSocket';
const webSocket = ref();
//实例化
webSocket.value = getWebSocket();
// webSocket接收数据
webSocket.value.getWS().onmessage = (mes) => {
}
//发送数据
webSocket.value.sendMessage(JSON.stringify(toRaw('数据')));
//关闭
webSocket.value.getWS().close();