简单的WebSocket对话

步骤

  1. 选择一个WebSocket服务器,这里选择到的模块是ws模块

npm i ws

  1. 创建一个 WebSocket 服务器 新建一个 server.js 编写如下代码

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 3000 });

wss.on('connection', (socket) => {
  console.log('Client connected');

  socket.on('message', (message) => {
    console.log(`Received message: ${message}`);

    // 回复消息
    const reply = `You said: ${message}`;
    socket.send(reply);
  });

  socket.on('close', () => {
    console.log('Client disconnected');
  });
});

  1. 这时候我们需要一个页面进行发送消息,所以新建一个index.html代码如下

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>WebSocket Chat</title>
</head>
<body>
  <div id="messages"></div>
  <form id="message-form">
    <input type="text" id="message-input">
    <button type="submit">Send</button>
  </form>

  <script>
    const socket = new WebSocket('ws://localhost:3000');
    let flag = false
    socket.addEventListener('open', (event) => {
      console.log('Connected to WebSocket server');
    });
    socket.addEventListener('message', (event) => {
      if(flag) { // 是我方的话不走以下
        flag = false
        return
      }
      const message = event.data
      if (message instanceof Blob) {
        const reader = new FileReader();
        reader.readAsText(message);
        reader.onload = () => {
          const text = reader.result;
          displayMessage(text, '对方');
        };
      } else {
        displayMessage(message);
      }
    })
    socket.addEventListener('close', (event) => {
      console.log('Disconnected from WebSocket server');
    });

    const form = document.getElementById('message-form');
    const input = document.getElementById('message-input');
    const messages = document.getElementById('messages');
    
    form.addEventListener('submit', (event) => {
      event.preventDefault();
      const message = input.value;
      input.value = ''
      flag = true
      socket.send(message);
      displayMessage(message, '我');
    });

    function displayMessage(message, name) {
      const p = document.createElement('p');
      p.textContent = name+': '+message;
      messages.appendChild(p);
    }
  </script>
</body>
</html>


这个HTML页面包含了一个消息输入框和一个发送按钮,当用户在输入框中输入消息并点击发送按钮时,会将消息发送到WebSocket服务器,并将其显示在页面上
通过 socket.send 来发送消息、通过 socket.addEventListener 来监听页面收到的消息、通过 displayMessage 函数来将消息显示在页面上
nodejs 来启动 server.js 如下 node serve.js
在单独打开两个 index.html 就能进行对话了

posted @ 2023-06-09 09:46  王小美丶  阅读(34)  评论(0编辑  收藏  举报