let socket;
|
|
export default {
|
install: (Vue, options) => {
|
Vue.prototype.$connectWebSocket = (viewname, handleData) => {
|
if (typeof WebSocket === "undefined") {
|
console.log("您的浏览器不支持 WebSocket");
|
} else {
|
let socketUrl = "ws://" + options.ip + ":8888" + "/springboot-vue3/api/talk/" + viewname;
|
if (socket != null) {
|
socket.close();
|
socket = null;
|
}
|
|
// 开启一个 WebSocket 连接
|
socket = new WebSocket(socketUrl);
|
|
// 打开事件
|
socket.onopen = () => {
|
console.log("WebSocket 已打开");
|
};
|
|
// 收到消息
|
socket.onmessage = (msg) => {
|
if (!msg.data) {
|
return;
|
}
|
handleData(JSON.parse(msg.data));
|
};
|
|
// 关闭事件
|
socket.onclose = () => {
|
console.log("WebSocket 已关闭");
|
};
|
|
// 发生错误事件
|
socket.onerror = () => {
|
console.log("WebSocket 发生了错误");
|
};
|
}
|
};
|
|
Vue.prototype.$sendWebSocketMessage = (message) => {
|
socket?.send(JSON.stringify(message));
|
};
|
|
Vue.prototype.$closeWebSocket = () => {
|
// 关闭 WebSocket 连接
|
socket.close();
|
};
|
},
|
};
|