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>
相关推荐
freewlt21 小时前
Monorepo 架构下的前端工程化实践:pnpm + Turborepo 从入门到落地
前端·arcgis·架构
Boop_wu1 天前
[Java 算法] 字符串
linux·运维·服务器·数据结构·算法·leetcode
徐小夕1 天前
我用 AI 撸了个开源"万能预览器":浏览器直接打开 Office、CAD 和 3D 模型
前端·vue.js·github
m0_694845571 天前
Dify部署教程:从AI原型到生产系统的一站式方案
服务器·人工智能·python·数据分析·开源
小码哥_常1 天前
Flutter Android 延迟加载代码指南:提升应用性能的关键
前端
这是个栗子1 天前
TypeScript(三)
前端·javascript·typescript·react
kvo7f2JTy1 天前
基于机器学习算法的web入侵检测系统设计与实现
前端·算法·机器学习
北风toto1 天前
前端CSS样式详细笔记
前端·css·笔记
nanfeiyan1 天前
git commit
前端
码云数智-大飞1 天前
C++ RAII机制:资源管理的“自动化”哲学
java·服务器·php