首先需要后端提供类似于如下的 websocket path:

// ws://{host}/{path}
// eg:
private websocketPath: string = 'ws://t.bsapi.xxx.com/xxx-service/webSocket/user1';

然后在组件中创建 websocket:


全局就在 App.vue 中即可


<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';

@Component()
export default class extends Vue {

private websocketPath: string = 'ws://t.bsapi.xxx.com/xxx-service/webSocket/user1';
private socket: any = null;
private socketHeartCheck: any = {
timeout: 5000,
timeoutObj: null,
};

initWebsocket() {
if (typeof WebSocket === 'undefined') {
console.log('您的浏览器不支持socket');
} else {
// 实例化socket
this.socket = new WebSocket(this.websocketPath);
// 监听socket连接
this.socket.onopen = this.onSocketOpen;
// 监听socket错误信息
this.socket.onerror = this.onSocketError;
// 监听socket消息
this.socket.onmessage = this.onSocketMessage;
this.socket.onclose = this.onSocketClose;
}
}

onSocketOpen() {
console.log('socket连接成功');
clearInterval(this.socketHeartCheck.timeoutObj);
this.socketHeartCheck.timeoutObj = setInterval(() => {
this.socket.send('HeartBeat');
}, this.socketHeartCheck.timeout);
}
onSocketError(err: any) {
console.log('socket连接错误', err);
}
onSocketMessage(msg: any) {
console.log('socket message', msg);
if (!msg.data || msg.data === '连接成功') return;
try {
const msgObj = JSON.parse(msg.data);
this.$notify.info({
title: msgObj.title,
message: msgObj.msg,
});
} catch (err) {
console.log('转换 socket 消息失败:', err);
}
}
onSocketClose() {
console.log('socket已经关闭');
}

mounted() {
this.initWebsocket();
}
destroyed() {
clearInterval(this.socketHeartCheck.timeoutObj);
this.socket.onclose();
}
}
</script>

码字不易,觉得有帮助的小伙伴点个赞鼓励下~

Vue 中使用 Websocket Demo_socket

扫描上方二维码关注我的订阅号~