效果图

html客户端接受的消息

接下来开始实现服务端
创建server.js
- const WebSocket = require('ws');
-
- const wss = new WebSocket.Server({ port: 8877 });
-
- wss.on('connection', function connection(ws) {
- console.log('WebSocket connection opened.');
-
- // 每隔 5 秒发送一次消息
- const interval = setInterval(function() {
- const message = {
- departName: "不健康科室",
- patientName1: "不健康人1",
- patientName2: "11111",
- patientName3: "王五",
- patientName4: "赵六",
- patientName5: "小明",
- patientName6: "小红"
- };
-
- // 将 JavaScript 对象转换为 JSON 字符串
- const jsonMessage = JSON.stringify(message); // 要发送的消息内容
- console.log('Sending message', jsonMessage);
- ws.send(jsonMessage); // 发送 JSON 字符串
- }, 5000);
-
- ws.on('close', function close() {
- console.log('WebSocket connection closed.');
- clearInterval(interval);
- });
- });
接下来,安装 ws 模块,它是一个 WebSocket 库,用于创建 WebSocket 服务器。你可以通过运行 npm install ws 命令来安装它。
cmd命令 执行 “npm install ws”
安装好后生成的文件

cmd命令终端中运行 node server.js 启动服务器
html客户端代码
- html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>WebSocket Clienttitle>
- head>
- <body>
- <script>
- const ws = new WebSocket('ws://localhost:8877');
-
- ws.onopen = function() {
- console.log('WebSocket connected');
- };
-
- ws.onmessage = function(event) {
- console.log('Received message from server:', event.data);
- };
- script>
- body>
- html>
直接浏览器打开html就可以看到效果
