export default {
data(){
return {
msgList: [],
youIcon:"", //对方头像
myIcon:"", //我的头像
socket: "", //socket建立的连接
}
},
mounted() {
this.initWebSocket();
},
// 开启(初始化websocket)
initWebSocket() {
if (typeof WebSocket === "undefined") {
alert("您的浏览器不支持socket");
} else {
this.path = "后端给的socket链接",
// 实例化socket
this.socket = new WebSocket(this.path);
// 监听socket连接
this.socket.onopen = this.open;
// 监听socket错误信息
this.socket.onerror = this.error;
// 监听socket消息
this.socket.onmessage = this.message;
//监听socket断开连接消息
this.socket.onclose = this.close;
}
},
open() {
console.log("socket连接成功--websocketOpen");
},
error() {
console.log("连接错误--websocketError");
},
close() {
console.log("socket已经关闭--websocketClose");
},
message(e) {
console.log("后端发来了信息--websocketMessage");
console.log(JSON.parse(e.data));
this.msgList.push({content:"你吃了吗?"}); //根据后端返回的格式展示消息
},
}
vue使用websocket写聊天室
最新推荐文章于 2024-08-27 10:52:38 发布
本文介绍了如何使用WebSocket技术在前端实现与后端的实时双向通信,包括WebSocket的初始化、错误处理和消息监听。重点展示了初始化WebSocket连接、处理socket状态变化及解析后端推送的消息的过程。
摘要由CSDN通过智能技术生成