打赏

vue+websocket demo 实例

vue+websocket demo:


<!-- vue + websocket连接demo -->
<template>
    <div>
        <h1>vue + websocket连接demo</h1>
        <Button @click="test">test</Button>
    </div>
</template>

<script>
let socket;
// 给服务器发送一个字符串:
export default {
    data() {
        return {
            // 连接标志位
            lockReconnect: false,
            wsCfg: {
                // websocket地址
                url: "ws://127.0.0.1:8081"
            }
        };
    },
    methods: {
        createWebSocket() {
            try {
                // 创建Web Socket 连接
                socket = new WebSocket(this.wsCfg.url);
                // 初始化事件
                this.initEventHandle(socket);
            } catch (e) {
                // 出错时重新连接
                this.reconnect(this.wsCfg.url);
            }
        },
        initEventHandle(socket) {
            // 连接关闭时触发
            socket.onclose = () => {
                console.log("连接关闭");
            };
            // 通信发生错误时触发
            socket.onerror = () => {
                // 重新创建长连接
                this.reconnect();
            };
            // 连接建立时触发
            socket.onopen = () => {
                console.log("连接成功");
            };
            // 客户端接收服务端数据时触发
            socket.onmessage = msg => {
                // 业务逻辑处理
                console.log(msg.data, "ws:data");
            };
        },
        reconnect() {
            if (this.lockReconnect) {
                return;
            }
            this.lockReconnect = true;

            // 没连接上会一直重连,设置延迟避免请求过多
            setTimeout(() => {
                this.lockReconnect = false;
                this.createWebSocket(this.wsCfg.url);
            }, 2000);
        },
        test() {
            // 给服务器发送一个字符串:
            // ws.send("Hello!");
            socket.send("Hello!");
        }
    },
    mounted() {
        this.createWebSocket();
    }
};
</script>
 

 

 

node 服务端启websocket服务:

// 导入WebSocket模块:
const WebSocket = require('ws');

// 引用Server类:
const WebSocketServer = WebSocket.Server;

// 实例化:
const wss = new WebSocketServer({
    port: 8081
});

wss.on('connection', function (ws) {
    console.log(`[SERVER] connection()`);
    ws.on('message', function (message) {
        console.log(`[SERVER] Received: ${message}`);
        ws.send(`ECHO: ${message}`, (err) => {
            if (err) {
                console.log(`[SERVER] error: ${err}`);
            }
        });
    })
});

运行前后端代码:

 

 

 前端页面可以看到发送websocket数据后,接收到了后端的数据,实现了双向通信。

 

 

更新:2021.14 

服务端群发消息:

 

// 导入WebSocket模块:
const WebSocket = require('ws');

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

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(data) {
    wss.clients.forEach(function each(client) {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(data);
      }
    });
  });
});

 

posted @ 2019-08-08 11:46  孟繁贵  阅读(6695)  评论(3编辑  收藏  举报
TOP