欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 艺术 > nodejs后端ws与http结合共享一个服务器,前端websocket发送信息后端ws接收信息,使用Map定型数组设置ID

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

2025/2/5 12:41:59 来源:https://blog.csdn.net/cdcdhj/article/details/145150483  浏览:    关键词:nodejs后端ws与http结合共享一个服务器,前端websocket发送信息后端ws接收信息,使用Map定型数组设置ID

//服务端代码

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的IDclients.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');
})

//客户端代码

<!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>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com