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 => { // 监听频道,等待消息
});