vue使用websocket写聊天室

本文介绍了如何使用WebSocket技术在前端实现与后端的实时双向通信,包括WebSocket的初始化、错误处理和消息监听。重点展示了初始化WebSocket连接、处理socket状态变化及解析后端推送的消息的过程。
摘要由CSDN通过智能技术生成
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:"你吃了吗?"}); //根据后端返回的格式展示消息
    },
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值