实现一个简单的websocket

实现简单的websocket,只需要几步:

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

index.html



    
    
    Document


    
  • {{i+1}}.{{item}}
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............');
})

你可能感兴趣的:(node.js,websocket)