当前位置:   article > 正文

vue2 实现原生 WebSocket_vue2创建一个简单的websocket服务器。

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();
    }
  }
};

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/844228
推荐阅读
相关标签
  

闽ICP备14008679号