效果:
准备工作:
新建一个文件夹,在根目录安装依赖:
npm install ws express
依赖介绍:
WS是一个轻量级、高效的WebSocket库,适用于Node.js环境。
express 是一个流行的Node.js Web应用程序框架。
新建server.js文件,和public文件夹,public下新建index.html:
server.js:
介绍:PORT为运行端口,看板地址为http://localhost: + PORT,连接地址为ws://localhost:+ PORT
javascript
const express = require('express');
const WebSocket = require('ws');
const app = express();
const PORT = 3000;
// 创建 HTTP 服务
app.use(express.static(__dirname + '/public'));
const server = app.listen(PORT, () => {
});
// 创建 WebSocket 服务
const wss = new WebSocket.Server({ server });
let clients = [];
wss.on('connection', (ws) => {
clients.push(ws);
console.log(`New client connected. Total clients: ${clients.length}`);
// 监听客户端消息
ws.on('message', (message) => {
console.log(`Received message: ${message}`);
try {
const parsedMessage = JSON.parse(message);
if (parsedMessage.command === "ping") {
ws.send(JSON.stringify({ command: "pong", data: "pong response" }));
}
} catch (e) {
// 若消息不是 JSON 格式的字符串,直接处理为普通消息
ws.send(`Echo: ${message}`);
}
});
// 当客户端断开连接时,从列表中移除并记录信息
ws.on('close', () => {
clients = clients.filter((client) => client !== ws);
console.log(`Client disconnected. Total clients: ${clients.length}`);
});
});
// 定义推送消息的函数,广播给所有客户端
function broadcastMessage(message) {
clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
}
// 定义 API 接口用于前端推送消息
app.use(express.json());
app.post('/send', (req, res) => {
const message = req.body.message;
// 广播消息给所有客户端
broadcastMessage(message);
res.json({ status: 'Message sent' });
});
index.html:
介绍:可以根据自己测试的需要改变sendMessage发送的格式
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WebSocket Client</title>
<style>
#messages {
border: 1px solid #ccc;
padding: 10px;
height: 200px;
overflow-y: auto;
margin-bottom: 10px;
}
.message {
margin: 5px 0;
padding: 5px;
}
.sent {
color: green;
}
.received {
color: black;
}
.status {
color: blue;
}
.item{
font-size: 12px;
margin: 10px 0 ;
display: flex;
align-items: center;
}
</style>
</head>
<body>
<div class="item">
指令:
<input type="text" id="command" placeholder="输入command" />
</div>
<div class="item">
数据:
<input type="text" id="data" placeholder="输入data" />
</div>
<button onclick="sendMessage()">发送</button>
<div id="messages"></div>
<script>
// WebSocket 连接
const ws = new WebSocket("ws://localhost:3000");
// 监听连接成功
ws.onopen = () => {
displayMessage("Connected to WebSocket server", 'status');
};
// 监听消息
ws.onmessage = (event) => {
const receivedData = event.data;
displayMessage(receivedData, 'received');
};
// 发送消息
function sendMessage() {
const command = document.getElementById("command").value;
const data = document.getElementById("data").value;
if (command) {
ws.send(JSON.stringify({
command
})); // 发送消息到 WebSocket 服务器
displayMessage(command, 'sent'); // 显示发送的消息
// 通过 HTTP POST 向后端发送消息
fetch('http://localhost:3000/send', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ message: JSON.stringify({
command,
data:data ?? {}
}) })
}).then(response => response.json())
.then(data => console.log(data));
}
document.getElementById("message").value = ""; // 清空输入框
}
// 显示消息
function displayMessage(message, type) {
const messagesDiv = document.getElementById("messages");
const newMessage = document.createElement("div");
newMessage.className = `message ${type}`;
newMessage.textContent = `${type === 'sent' ? '发送' : type === 'received' ? '接收' : '状态'}: ${message}`;
messagesDiv.appendChild(newMessage);
messagesDiv.scrollTop = messagesDiv.scrollHeight;
}
</script>
</body>
</html>
使用:
根目录执行命令:node server
表单用浏览器访问:http://localhost:3000/
接收端WebSocket连接地址ws://localhost:3000也可以改成IP
接收端WebSocket我写过Android和uniapp的,可以参考下列文章: