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>
相关推荐
程序员爱钓鱼7 分钟前
Go语言中的反射机制 — 元编程技巧与注意事项
前端·后端·go
南瓜胖胖14 分钟前
【seismic unix 合并两个su文件】
服务器·unix
GIS之路28 分钟前
GeoTools 结合 OpenLayers 实现属性查询(二)
前端·信息可视化
烛阴36 分钟前
一文搞懂 Python 闭包:让你的代码瞬间“高级”起来!
前端·python
AA-代码批发V哥39 分钟前
HTML之表单结构全解析
前端·html
聪聪的学习笔记1 小时前
【1】确认安装 Node.js 和 npm版本号
前端·npm·node.js
小磊哥er1 小时前
【前端工程化】你知道前端编码规范包含哪些内容吗
前端
weixin_399380691 小时前
k8s一键部署tongweb企业版7049m6(by why+lqw)
java·linux·运维·服务器·云原生·容器·kubernetes
阿巴~阿巴~1 小时前
Linux基本命令篇 —— uname命令
linux·运维·服务器
菌菇汤1 小时前
uni-app实现单选,多选也能搜索,勾选,选择,回显
前端·javascript·vue.js·微信小程序·uni-app·app