node 的依赖包
node 中实现 websocket 的依赖包有很多,websocket、ws 均可,本文选取 ws 来实现,首先安装依赖
- npm install ws
聊天室实例
假如 A,B,C,D 用户均通过客户端连接到 Websocket 服务,其中每个人发的消息都需要将其通过 Websocket 转发给其他人,此场景类似于服务端将 A 的消息广播给组内其他用户。
服务端实现
首先来看服务端程序,具体的工作流程分以下几步:
服务端代码
- var WebSocketServer = require('ws').Server,
- wss = new WebSocketServer({
- port: 8080
- });
- // 连接池
- var clients = [];
- wss.on('connection',
- function(ws) {
- // 将该连接加入连接池
- clients.push(ws);
- ws.on('message',
- function(message) {
- // 广播消息
- clients.forEach(function(ws1) {
- if (ws1 !== ws) {
- ws1.send(message);
- }
- })
- });
- ws.on('close',
- function(message) {
- // 连接关闭时,将其移出连接池
- clients = clients.filter(function(ws1) {
- return ws1 !== ws
- })
- });
- });
客户端实现
- <html>
- <input type="text" id="text">
- <input type="button" onclick="sendMessage()" value="online">
- <script>
- var ws = new WebSocket("ws://localhost:8080");
- ws.onopen = function (e) {
- console.log('Connection to server opened');
- }
- ws.onmessage = function(event) {
- console.log('Client received a message', event);
- };
- ws.onclose = function (e) {
- console.log('connection closed.');
- }
- function sendMessage() {
- ws.send(document.getElementById('text').value);
- }
- </script>
- </html>
如何发现用户?
通过上述的 demo 可以看到,WebSocket 都是基于连接的,也就是说我们知道 data 是从那个 connection 发过来,但并不知道使用客户端的是李雷或者韩梅梅,这可如何是好?再想另一种场景,李雷只想给韩梅梅发消息,不想将消息广播给其他客户端,此时我们就需要在 Server 端能够标识用户身份和连接的对应关系。
于是,需要在客户端连接到 WebSocket 之后,紧接着再发一次请求,告诉 Server 我的 user_id 是多少,Server 将此 user_id 与 connection 之间的关系存储在 hashmap 中,至此就建立了 user_id 与 connection 的对应关系。当需要发送消息给对应的客户端,从此 hashmap 中取出对应用户的 connection 信息,调用其 send 方法发出消息即可。
依赖包
- npm install hashmap
服务端实现
- var WebSocketServer = require('ws').Server,
- webSocketServer = new WebSocketServer({
- port: 8080
- });
- var HashMap = require('hashmap');
- // record the client
- var userConnectionMap = new HashMap();
- var connectNum = 0;
- // connection
- webSocketServer.on('connection',
- function(ws) {++connectNum;
- console.log('A client has connected. current connect num is : ' + connectNum);
- ws.on('message',
- function(message) {
- var objMessage = JSON.parse(message);
- var strType = objMessage['type'];
- switch (strType) {
- case 'online':
- userConnectionMap.set(objMessage['from'], ws);
- break;
- default:
- var targetConnection = userConnectionMap.get(objMessage['to']);
- if (targetConnection) {
- targetConnection.send(message);
- }
- }
- });
- ws.on('close',
- function(message) {
- var objMessage = JSON.parse(message);
- userConnectionMap.remove(objMessage['from']);
- });
- });
来源: http://www.jb51.net/article/108123.htm