现在很多项目都需要内嵌一个简单的即时通讯模块,做用户之间的快速沟通,我们昨天也实现了一个,用的socket.io这个插件,可以去npm网站下载或直接npm安装。
现在把最简配置贴出来,以备参考:
首先是服务端的route.js
const express = require('express')
const app = express()
const server = require('http').Server(app)
const io = require('socket.io')(server)
//在线用户
var onlineUsers = {};
//当前在线人数
var onlineCount = 0;
io.on('connection', function (conn) {
conn.on('login', function (obj) {
console.log('login', obj);
if (!onlineUsers.hasOwnProperty(obj.userid)) {
onlineUsers[obj.userid] = {
id: obj.userid,
conn: conn
};
onlineCount++;
}
});
conn.on('disconnect', function () {
if (onlineUsers.hasOwnProperty(conn.userid)) {
var obj = {
id: obj.userid,
conn: conn
};
delete onlineUsers[conn.userid];
onlineCount--;
}
});
conn.on('sendMsg', function (data) {
var rids = data.to.split(',')
for (let id of rids) {
if (id) {
var receiver = onlineUsers[id]
if (receiver) {
receiver.conn.emit('receiveMsg', data.msg)
}
}
}
})
});
server.listen('3000', () => {
console.log('open Browser on http://127.0.0.1:3000')
})
然后是网站前端的页面调用,这里注意也要使用socket.io的客户端js插件,建议下载下来:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="/public/socket.io.js"></script>
<title>Document</title>
</head>
<body>
<div>
<div>
<div>
<h1>WebSocket chat,欢迎使用:</h1>
</div>
<div>
<label>输入用户名:</label>
<input type="text" id="name" />
<button id="conn">连接</button>
<label>输入聊天对象用户名:</label>
<input type="text" id="talkname" />
</div>
<div>
<div id="messages"></div>
</div>
<hr>
<div>
<input type="text" id="msg" />
<button id="send">发送</button>
</div>
</div>
</div>
<script>
var user = document.getElementById("name");
var talk = document.getElementById("talkname");
var btnConn = document.getElementById("conn");
var msgs = document.getElementById("messages");
var btnSend = document.getElementById("send");
var txtMsg = document.getElementById("msg");
var pattern = /^[\u4e00-\u9fa5]{2,10}$/;
btnConn.onclick = function () {
// if (!pattern.test(input.value)) {
// alert("名称不能为空且必须为中文");
// return;
// }
var ws = io('ws://localhost:9001');
ws.on('receiveMsg', function (data) {
msgs.innerHTML += new Date().toUTCString() + ":" + data + "<br>";
})
ws.on('connect', function (e) {
console.log("连接服务器成功");
ws.emit('login',{userid: user.value});
})
send.onclick = function (e) {
var txt = txtMsg.value;
txtMsg.value = '';
ws.emit('sendMsg',{from: user.value, to: talk.value, msg: txt});
}
document.onkeydown = function (e) {
e = e || window.event;
if (e.keyCode == 13) {
send.onclick();
return false;
}
}
}
</script>
</body>
</html>
整个过程非常简单,跟微软提供的SignalR实现过程非常相似