WebSoker-Server

96 阅读1分钟

Nodejs实现WebSoker通信server端

代码示例

const WebSocket = require('ws');
const http = require('http');
const fs = require('fs');

const server = http.createServer((req, res) => {
  if (req.url === '/') {
    const html = fs.readFileSync('client.html', 'utf-8');
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(html);
  }
});

const wss = new WebSocket.Server({ server });
const clients = new Map();
let clientIdCounter = 1;

wss.on('connection', (ws) => {
  const clientId = Number(clientIdCounter++);
  console.log('新用户'+clientId+'进入');
  clients.set(clientId, ws);

  ws.on('message', (message) => {
    console.log(`收到客户端 ${clientId} 消息: ${message}`);
    const messageString = String(message);

    // 检查是否是针对特定客户端的指令
    if (messageString.startsWith('/sendto ')) {
      const [, targetClientId, targetMessage] = messageString.split(' ');
      const targetClient = clients.get(Number(targetClientId));
      
      if (targetClient) {
        console.log(`给客户端 ${targetClientId} 发送消息: ${targetMessage}`);
        targetClient.send(`来自客户端 ${clientId}: ${targetMessage}`);
      } else {
        console.log(`找不到目标客户端 ${targetClientId}`);
      }
    } else {
      clients.forEach(client => {
        if (client.readyState === WebSocket.OPEN) {
          console.log(`给所有客户端发送 ${messageString}`);
          client.send(`来自客户端 ${clientId}: ${messageString}`);
        }
      });
    }
  });

  ws.on('close', () => {
    console.log(`客户端 ${clientId} 断开连接`);
    clients.delete(clientId);
  });
});

const port = 3000;
server.listen(port, () => {
  console.log('Server is listening on port ' + port);
});