用socket实现简单的用户和用户之间的通信。
用到的库socket.io
服务端
服务端逻辑: 用户连接以后将连接信息存储到userConnections中,key是用户ID。当发送消息时传参的target是目标用户的名称,当userConnections中存在时就说明用户在线。取出target的连接将内容发送。
初始化项目并安装依赖
npm init -y
npm i socket.io
import { Server } from "socket.io";
const io = new Server(3000, {
cors: {
origin: "*",
},
});
const userConnections = {};
io.on("connection", (socket) => {
const userId = socket.handshake.query.userId;
// 将连接存储到映射中
userConnections[userId] = socket;
// 接收客户端的消息
socket.on("sendMessage", ({ target, content }) => {
// 判断用户在线
if (userConnections[target]) {
// 发送消息
userConnections[target].emit("receiveMessage", {
from: userId,
content,
});
} else {
console.log("用户不在线", target);
}
});
socket.on("disconnect", () => {
delete userConnections[userId];
});
});
页面
输入自己用户名,然后将要接收消息的用户名输入到target中,就可以实现通信了
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="u">
<input id="userId" type="text" placeholder="用户名">
<button id="createConn">登录</button>
</div>
<div id="c" style="display: none;">
<input id="target" type="text" placeholder="对方用户名">
<input id="content" type="text" placeholder="消息内容">
<button id="sendMsg">发送消息</button>
</div>
</body>
</html>
<script type="module">
import { io } from "https://cdn.socket.io/4.7.5/socket.io.esm.min.js"
document.addEventListener("DOMContentLoaded", () => {
const createConn = document.querySelector('#createConn');
const target = document.querySelector('#target')
const content = document.querySelector('#content')
let socket;
createConn.addEventListener('click', () => {
const userId = document.querySelector('#userId');
const u = document.querySelector('#u');
const c = document.querySelector('#c');
u.style.display = 'none'
c.style.display = 'block'
socket = io("http://localhost:3000/", { query: { userId: userId.value } })
m()
})
const sendMsg = document.querySelector('#sendMsg');
sendMsg.addEventListener('click', () => {
socket.emit('sendMessage', { target: target.value, content: content.value })
})
function m() {
socket.on('receiveMessage', ({ from, content }) => {
console.log(from, content);
})
}
})
</script>