需要安装websocket插件
npm install websocket
启动
运行node server.js命令
代码
/**
* webSocket服务端
* 启动 node server.js
*/
const WebSocket = require('websocket').server;
const http = require('http');
// 创建 HTTP 服务器
const server = http.createServer(function(request, response) {
// 处理 HTTP 请求
});
// 监听端口号
server.listen(11341, function() {
console.log('Server is listening on port 11341');
});
// 创建 WebSocket 服务器
const wsServer = new WebSocket({
httpServer: server
});
// 存储所有连接的客户端
const clients = {};
wsServer.on('request', function(request) {
// 接受连接请求
const connection = request.accept(null, request.origin);
// 生成一个客户端ID,并将连接存储到clients中
const clientId = Date.now();
clients[clientId] = connection;
// 监听message事件,当接收到客户端的消息时,广播给其他客户端
connection.on('message', function(message) {
const msg = message.utf8Data;
console.log('Received Message:', msg);
for (const id in clients) {
if (id !== clientId) {
clients[id].sendUTF(msg);
}
}
});
// 监听close事件,当客户端关闭连接时,删除对应的连接记录
connection.on('close', function(reasonCode, description) {
console.log('Client has disconnected.');
delete clients[clientId];
});
});