node中使用socket.io实现简易网络聊天室
需要的包
"dependencies": {
"express": "^4.17.1",
"socket.io": "^2.3.0"
}
<script src="https://cdn.bootcss.com/socket.io/2.2.0/socket.io.js"></script>
前端网页
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>通讯socket</title>
<script src="https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js"></script>
</head>
<body>
<input type="text" id="roomInp" placeholder="请先输入你要加入的房间id"><br>
<button onclick="joinRoomFn()">点击先加入房间, 才能开始聊天</button><br>
<input type="text" placeholder="请输入你的昵称" id="userInp"><br>
<input type="text" placeholder="请输入你的聊天信息" id="myInp"><br>
<button onclick="send()">点我发送消息</button><br>
<div id="result">
</div>
<script src="https://cdn.bootcss.com/socket.io/2.2.0/socket.io.js"></script>
<script>
//1 加入房间 连接即时通讯服务器 传入房间id
let socket;
function joinRoomFn(){
let theRoomId = $("#roomInp").val();
if(theRoomId == ''){alert('房间号不能为空!');return;}
socket = io(`http://127.0.0.1:3000?roomid=${theRoomId}`);
socket.on("send_to_client",(arg)=>{// 接收欢迎消息
alert(arg);
})
socket.on("client_message",(obj)=>{
let {nickName,message} = obj;
let elStr =`<p>${nickName}说: ${message}</p>`;
$("#result").html($("#result").html() + elStr);
})
}
//2 发送消息
function send(){
if(socket === undefined){
alert("请先连接房间");
}else{
socket.emit("news",{
userName:$("#userInp").val(),
msg: $("#myInp").val(),
roomid: $("#roomInp").val()
});// 触发后台的news事件, 把值传给后台
}
}
</script>
</body>
</html>
后端server.js
const express = require('express');
const app = express();
// 在express应用上集成即时通信
const server = app.listen(3000);
// 1. 引入socket.io, 传入服务器对象, 让socket.io注入到web网页服务里
const io = require("socket.io")(server);
// 2. 监听浏览器端的连接事件 (是socket的连接, 而非地址的访问)
io.on('connect',(WebSocketObj)=>{// connect是固定的, 叫连接的事件
//1接收前端url传递过来的房间id
let {query:{roomid}} = WebSocketObj.handshake;
console.log(WebSocketObj.handshake['query']);
// query: { roomid: '1111', EIO: '3', transport: 'polling', t: 'N9LoXzC' }
WebSocketObj.join(roomid,()=>{ //2加入指定房间
WebSocketObj.emit("send_to_client",`恭喜加入 ${roomid} 房间成功!`);
});
WebSocketObj.on("news",(data)=>{//3监听前端发送消息, 前端需要传递roomId过来, 要广播给这个房间内所有的人
console.log(data)
io.to(data['roomid']).emit("client_message",{// io.to()里传入的是房间号, 代表只给这个房间号里的浏览器连接对象, 触发client_message事件
nickName:data['userName'],
message:data['msg']
});
});
})
服务器日志
{ roomid: '123', EIO: '3', transport: 'polling', t: 'N9MEqxf' }
{ roomid: '123', EIO: '3', transport: 'polling', t: 'N9MEuhp' }
{ userName: 'ss', msg: 'sssssssssss', roomid: '123' }
{ userName: 'dd', msg: 'dddddddddd', roomid: '123' }
本文来自博客园,作者:JackieDYH,转载请注明原文链接:https://www.cnblogs.com/JackieDYH/p/17634688.html