关于websocket的一些了解

6/12/2024 Websocket

创建一个WebSocket服务文件,用于封装WebSocket的相关操作

export default class WebSocketService {
  constructor(url) {
    this.url = url;
    this.ws = null;
    this.connect();
  }

  connect() {
    this.ws = new WebSocket(this.url);

    // 监听连接打开事件
    this.ws.onopen = () => {
      console.log('WebSocket连接成功');
    };

    // 监听消息事件
    this.ws.onmessage = (event) => {
      console.log('收到消息:', event.data);
    };

    // 监听连接关闭事件
    this.ws.onclose = (event) => {
      console.log('WebSocket连接关闭:', event);
      // 尝试重新连接
      setTimeout(() => {
        this.connect();
      }, 3000); // 3秒后重新连接
    };

    // 监听连接错误事件
    this.ws.onerror = (error) => {
      console.error('WebSocket错误:', error);
      this.ws.close();
    };
  }

  sendMessage(message) {
    if (this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(message);
    } else {
      console.log('WebSocket连接未打开,无法发送消息');
    }
  }

  close() {
    this.ws.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

在vue中引用WebSocketService

<template>
  <div>
    <h1>Chat Room</h1>
    <input v-model="message" @keyup.enter="sendMessage" placeholder="Type a message" />
    <button @click="sendMessage">Send</button>
  </div>
</template>

<script>
import WebSocketService from './websocketService';

export default {
  data() {
    return {
      message: '',
      wsService: null
    };
  },
  created() {
    // 创建WebSocket服务实例
    this.wsService = new WebSocketService('ws://example.com/socket');
  },
  methods: {
    sendMessage() {
      this.wsService.sendMessage(this.message);
      this.message = '';
    }
  },
  beforeDestroy() {
    // 在组件销毁前关闭WebSocket连接
    if (this.wsService) {
      this.wsService.close();
    }
  }
};
</script>

<style scoped>
/* 你的样式 */
</style>
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
最后更新于: 2024年8月22日星期四晚上8点04分