1、演示
2、实现流程
安装依赖
npm i ws
服务端代码
const WebSocket = require('ws')// 创建一个 WebSocket 服务器,监听端口 3000 const wss = new WebSocket.Server({ port: 3000 })// 监听连接事件 wss.on('connection', function connection(ws) {console.log('客户端已连接')// 监听客户端发送的消息ws.on('message', function incoming(message) {console.log('收到消息', message.toString())// 原样将消息发送回客户端ws.send(message.toString())})// 监听连接关闭事件ws.on('close', function () {console.log('客户端断开连接')}) })
客户端代码
<!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>WebSocket Demo</title></head><body><h1>WebSocket Demo</h1><input type="text" id="messageInput" placeholder="发送消息" /><button onclick="sendMessage()">发送</button><ul id="messages"></ul><script>const socket = new WebSocket('ws://localhost:3000')// 监听连接打开事件socket.addEventListener('open', function (event) {console.log('服务端已连接')})// 监听接收消息事件socket.addEventListener('message', function (event) {console.log('收到信息', event.data)displayMessage(event.data)})// 将消息显示在页面上function displayMessage(message) {const messages = document.getElementById('messages')const li = document.createElement('li')li.textContent = messagemessages.appendChild(li)}// 发送消息到服务器function sendMessage() {const input = document.getElementById('messageInput')const message = input.valuesocket.send(message)input.value = ''}</script></body> </html>