以下是一个使用Node.js和WebSocket实现的简单聊天室案例:

  1. 安装依赖包
npm install ws express
  1. 创建一个服务器
const express = require('express');
const http = require('http');
const WebSocket = require('ws');

const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });

wss.on('connection', (ws) => {
  // 处理消息
  ws.on('message', (message) => {
    // 广播消息
    wss.clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(message);
      }
    });
  });
});

server.listen(8080, () => {
  console.log('Server started on port 8080');
});
  1. 创建一个前端页面
<!DOCTYPE html>
<html>
  <head>
    <title>WebSocket Chat</title>
  </head>
  <body>
    <div>
      <input type="text" id="message" />
      <button onclick="send()">Send</button>
    </div>
    <div id="messages"></div>

    <script>
      const socket = new WebSocket('ws://localhost:8080');

      // 处理消息
      socket.onmessage = (event) => {
        const messages = document.getElementById('messages');
        const message = document.createElement('div');
        message.innerText = event.data;
        messages.appendChild(message);
      };

      // 发送消息
      function send() {
        const messageInput = document.getElementById('message');
        const message = messageInput.value;
        messageInput.value = '';
        socket.send(message);
      }
    </script>
  </body>
</html>
  1. 运行服务器
node server.js
  1. 在浏览器中打开前端页面
http://localhost:8080

现在你可以在聊天室中发送消息,并且所有连接到该服务器的客户端都将收到这些消息。