vue2 实现原生 WebSocket

原生WebSocket: new WebSocket

WebSocket | ThinkTS官网

export default {
  data() {
    return {
      socket: null
    };
  },
  created() {
    // 1. 创建 WebSocket 实例
    this.socket = new WebSocket('ws://localhost:3000');

    // 2. 监听 WebSocket 连接打开事件
    this.socket.onopen = () => {
        console.log('当前客户端已连接');
    };

    // 3. 监听 WebSocket 消息事件
    this.socket.onmessage = (event) => {
        console.log('客户端接收的数据:', JSON.parse(event.data));
        
        // 4. 发送消息给服务端
        let post_data = {name: 'test'}
        this.socket.send(JSON.stringify(post_data))
    };

    // 5. 监听 WebSocket 关闭事件
    this.socket.onclose = () => {
        console.log('WebSocket closed');
    };

    // 6. 监听 WebSocket 错误事件
    this.socket.onerror = (error) => {
        console.log('WebSocket error:', error);
    };
  },
  methods: {
    // 发送消息按钮
    sendMessage(message) {
        // 4. 发送消息到 WebSocket 服务器
        this.socket.send(JSON.stringify(message))
    }
  },
  beforeDestroy() {
    // 关闭 WebSocket 连接
    if (this.socket) {
        this.socket.close();
    }
  }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值