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>
相关推荐
网络空间小黑22 分钟前
WEB渗透测试----信息收集
服务器·前端·网络·安全·web安全·网络安全
水银嘻嘻1 小时前
web 自动化之 Unittest 应用:报告&装饰器&断言
前端·python·自动化
巴巴_羊1 小时前
AJAX原理
前端·javascript·ajax
良木林1 小时前
HTML难点小记:一些简单标签的使用逻辑和实用化
前端·html
羑悻的小杀马特2 小时前
【Linux篇章】Linux 进程信号2:解锁系统高效运作的 “隐藏指令”,开启性能飞跃新征程(精讲捕捉信号及OS运行机制)
linux·运维·服务器·学习·os·进程信号
一个游离的指针2 小时前
ES6基础特性
前端·javascript·es6
layman05282 小时前
ES6/ES11知识点
前端·ecmascript·es6
Hello.Reader3 小时前
ngx_http_keyval_module动态键值管理
网络协议·nginx·http
爬树的小蚂蚁5 小时前
Linux 修改bond后网关不生效的问题
linux·运维·服务器
洁洁!5 小时前
从零开始在亚马逊云科技 EC2上部署DeepSeek R1大语言模型:完整实战指南
服务器·科技·语言模型