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>
相关推荐
五点六六六25 分钟前
基于 AST 与 Proxy沙箱 的局部代码热验证
前端·设计模式·架构
发现一只大呆瓜3 小时前
SSO单点登录:从同域到跨域实战
前端·javascript·面试
发现一只大呆瓜3 小时前
告别登录中断:前端双 Token无感刷新
前端·javascript·面试
Cg136269159743 小时前
JS-对象-Dom案例
开发语言·前端·javascript
无限大64 小时前
《AI观,观AI》:善用AI赋能|让AI成为你深耕核心、推进重心的“最强助手”
前端·后端
烛阴4 小时前
Claude Code Skill 从入门到自定义完整教程(Windows 版)
前端·ai编程·claude
va学弟4 小时前
Java 网络通信编程(6):视频通话
java·服务器·网络·音视频
lxh01134 小时前
数据流的中位数
开发语言·前端·javascript
神仙别闹5 小时前
基于NodeJS+Vue+MySQL实现一个在线编程笔试平台
前端·vue.js·mysql
zadyd6 小时前
Workflow or ReAct ?
前端·react.js·前端框架