乐趣区

关于node.js:实现一个简单的websocket

实现简略的 websocket,只须要几步:

  1. 引入 socket.io 组件;
  2. 前端初始化页面时,监听 socket.on(‘chatMsg’, () => xxx);
  3. 须要发送事件时,触发 socket.emit(‘chatMsg’, ‘msg’);
  4. 后端监听事件并回调即可

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <input type="text" id="name">
        <button type="button"  @click="submit">send</button>
        <ul v-for="(item, i) in msgList" :key="item + new Date().getTime()">
            <li>{{i+1}}.{{item}}</li>
        </ul>
    </div>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.0/axios.js"></script>
    <script src="https://lib.baomitu.com/vue/2.6.12/vue.js"></script>
    <script src="https://lib.baomitu.com/socket.io/3.0.1/socket.io.js"></script>
    <script>
        // 生成对象
        let socket = io();
        let vm = new Vue({
            el: '#app',
            data: {msgList: [],
            },
            created () {
                // 监听
                socket.on('chatMsg', (msg) => {vm.msgList.push(msg)
                })
            },
            methods: {submit: async () => {let msg = document.getElementById('name').value;
                    document.getElementById('name').value = '';

                    // 发送事件
                    socket.emit('chatMsg', msg);
                },
            }
        })
    </script>
</body>
</html>

index.js

const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);

app.get('/', (req, res) => {res.sendFile(__dirname + '/index.html');
})

// 监听
io.on('connection', (socket) => {console.log('a socket connection....');
    
    // 事件达到时
    socket.on('chatMsg', (msg) => {io.emit('chatMsg', msg);
    })
    
    // 链接断开时
    socket.on('disconnect', () => {console.log('disconnect');
    })
})

http.listen(3000, () => {console.log('http listen 3000............');
})
退出移动版