nodejs后端ws与http结合共享一个服务器,前端websocket发送信息后端ws接收信息,使用Map定型数组设置ID

//服务端代码

javascript 复制代码
const http=require('node:http');
const WebSocket=require('ws');

const server=http.createServer();
//创建websocket服务
const wss=new WebSocket.WebSocketServer({server});
//创建定型数组
const clients=new Map();

wss.on('connection',(ws)=>{
//设置ws的ID
    clients.set(ws,{id:Date.now()});
    //console.log('连接对象:',ws);
    ws.on('message',(message)=>{
        console.log(`接收到客户端信息:${clients.get(ws).id}:${message}`);
        //循环出clients中的ws对象,即客户端发送的信息对象
        for(let client of clients.keys())
        {
            if(client ===ws)
            {
                client.send(message.toString());
            }
        }
    });

    ws.on('close',()=>{
        
        console.log(`客户端${clients.get(ws).id}断开连接`);
        clients.delete(ws);
    });


});

server.listen(3000,'localhost',()=>{
    console.log('server is running on http://localhost:3000');
})

//客户端代码

javascript 复制代码
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html charset=utf-8"/>
        <title>websocket信息传递</title>
    </head>
    <body>
        <div id="msg">
            <input type="text" name="message" id="message" maxlength="33">
            <button id="sendbtn">发送</button>
        </div>
        
        <script type="text/javascript">
            const ws=new WebSocket('ws://localhost:3000');
            ws.onopen=function(){
                console.log('服务端已经连接');
            }
            ws.onmessage=function(event)
            {
                
                console.log(`接收到服务器的信息:${event.data}`);
            }
            ws.onclose=function(){
                console.log('服务器连接已断开');
            }
            

            const sendMsg=function(){
                const msg=document.getElementById('message').value;
                ws.send(msg);
                document.getElementById('message').value='';
            };
            document.getElementById('sendbtn').addEventListener('click',sendMsg);
        </script>
    </body>
</html>
相关推荐
web守墓人40 分钟前
【前端】ikun-markdown: 纯js实现markdown到富文本html的转换库
前端·javascript·html
小苹果135743 分钟前
阿里云mysql数据丢失,如何通过服务器备份在其他服务器上恢复数据,并获取mysql丢失数据,完成mysql数据恢复
服务器·mysql·阿里云
Savior`L1 小时前
CSS知识复习5
前端·css
许白掰1 小时前
Linux入门篇学习——Linux 工具之 make 工具和 makefile 文件
linux·运维·服务器·前端·学习·编辑器
hrrrrb2 小时前
【TCP/IP】12. 文件传输协议
服务器·网络·tcp/ip
安全系统学习5 小时前
网络安全之RCE分析与利用详情
服务器·网络·安全·web安全·系统安全
longze_75 小时前
Ubuntu连接不上网络问题(Network is unreachable)
linux·服务器·ubuntu
中微子5 小时前
🔥 React Context 面试必考!从源码到实战的完整攻略 | 99%的人都不知道的性能陷阱
前端·react.js
中微子6 小时前
React 状态管理 源码深度解析
前端·react.js