socket.io基本使用(express框架)

Server

const express = require("express");
const app = express();
const http = require("http").createServer(app);
const io = require("socket.io")(http);

io.on("connection", socket => {  // 客户端链接成功

    socket.on("监听频道", msg => {  // 监听的频道必须和客户端监听的频道相同,等待消息
        io.emit("监听频道", "发送的信息");  // 向所有客户端发送信息
    });

    io.on("disconnect", _ => {  // 客户端断开链接
        ...
    });

});

http.listen(3000, _ => {
    console.log("server running on 3000");
});


Client

    const io = io("url");
    io.emit("监听频道", "发送的信息");
    io.on("监听频道", msg => {  // 监听频道,等待消息

    });


posted @ 2019-07-21 21:35  枭苟  阅读(3996)  评论(0编辑  收藏  举报