# Websocket基础应用

# 基本的应用

  • 如何广播消息
  • 使用vue(调试版本&正式版本)

服务端:

const WebSocket = require('ws')

const wss = new WebSocket.Server({ port: 8000 })

wss.on('connection', function (ws) {
  console.log('a new client is connected!');
  ws.on('message', function (msg) {
    // 广播到其他的客户端
    wss.clients.forEach(function each(client) {
      // 广播给非自己的其他客户端
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(msg);
      }
    });
  })
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

在浏览器侧:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  </head>
  <body>
    <div id="app">
      <!-- 显示消息 -->
      <ul>
        <li v-for="item in items">
          {{ item.message }}
        </li>
      </ul>
      <!-- 发送消息 -->
      <div class="ctrl">
        <input type="text" v-model="inputValue" />
        <button type="button" @click="submit()">发送</button>
      </div>
      {{ inputValue }}
    </div>

    <script>
      // 客户端的代码
      // 1. 发送消息
      // 客户端 取input数据 -> websocket -> 发送到服务端 -> 转发给其他所有的客户端
      // 2. 显示消息
      var app = new Vue({
        el: "#app",
        data: {
          inputValue: "",
          items: [
            { message: "Foo" },
            { message: "Bar" },
            { message: "itheima" },
          ],
          wsHandle: "",
          name: "",
        },
        // 把元素挂载完成之后,自动执行
        mounted() {
          var _this = this;
          this.wsHandle = new WebSocket("ws://localhost:8000");
          this.wsHandle.onopen = this.onOpen;
          // 服务端发送回来的其他消息
          this.wsHandle.onmessage = this.onMessage;
        },
        methods: {
          submit: function() {
            // 取inputValue
            // 通过websocket发送数据
            console.log(this.inputValue);
            this.wsHandle.send(this.inputValue);
            this.items.push({
              message: this.inputValue,
            });
            this.inputValue = "";
          },
          onOpen: function() {
            console.log("client is connected");
          },
          onMessage: function(evt) {
            // 把数据推送到items中
            this.items.push({
              message: evt.data,
            });
          },
        },
      });
    </script>
  </body>
</html>
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
上次更新: 2020/10/28 下午11:02:30