首先先下载ws库
npm install ws
server.js [自定义websocket服务器,记得先用node启动]
const WebSocket = require('ws');const wss = new WebSocket.Server({ port: 8888 });wss.on('connection', function connection(ws) {console.log('Client connected');ws.on('message', function incoming(message) {console.log('Received: %s', message);// Broadcast the received message to all clientswss.clients.forEach(function each(client) {if (client !== ws && client.readyState === WebSocket.OPEN) {client.send(message);}});});
});
test.html
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Chat Application</title></head><body><div id="chat"></div><input type="text" id="messageInput" /><button onclick="sendMessage()">Send</button><script>// 简单测试const socket = new WebSocket("ws://localhost:8888");socket.onopen = () => {console.log("Connected to the server");};socket.onmessage = (event) => {const message = event.data;// 处理Blob消息if (message instanceof Blob) {const reader = new FileReader();reader.onload = function () {const text = reader.result;displayMessage(text); // 显示转换后的文本};reader.readAsText(message);} else {displayMessage(message); // 直接显示普通文本消息}};function displayMessage(message) {const chatElement = document.getElementById("chat");chatElement.innerHTML += `<p>${message}</p>`;}function sendMessage() {const messageInput = document.getElementById("messageInput");const message = messageInput.value.trim();if (message) {socket.send(message);messageInput.value = "";} else {alert("请输入消息");}}</script></body>
</html>
在两个不同的页面打开这个页面,可以发送消息,可以在另外一个页面接收并且正常显示出来