Advertisement
Guest User

WebSocket multipurpose chatserver for node.js

a guest
Feb 28th, 2013
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //WebSocket multipurpose chatserver
  2. //how it works: retransmits the message to all members of the current room
  3. //message packet format: stingified JSON with mandatory roomid field
  4. //other fields can be arbitrary data
  5.  
  6. var WebSocketServer = new require('ws');
  7. var webSocketServer = new WebSocketServer.Server({port: 8081});
  8. var clients = {}, rooms = {};
  9.  
  10. webSocketServer.on('connection', function(ws) {
  11.     var id = Math.ceil(Math.random()*(1<<30));
  12.     clients[id] = ws;
  13.     ws.on('message', function(rawmsg) {
  14.         try{
  15.             var packet = JSON.parse(rawmsg);
  16.             if('roomid' in packet) {
  17.                 var roomid = packet.roomid;
  18.                 if(!(roomid in rooms))rooms[roomid]=[];
  19.                 if(rooms[roomid].indexOf(clients[id])==-1) rooms[roomid].push(clients[id]);
  20.                 for(var c in rooms[roomid]){
  21.                     var cli = rooms[roomid][c];
  22.                     if(cli!=clients[id]) cli.send(rawmsg)
  23.                 }
  24.             }
  25.         }
  26.         catch(err){}
  27.     });
  28.     ws.on('close', function(){
  29.         for(var r in rooms) {
  30.             var cliind = rooms[r].indexOf(clients[id]);
  31.             if(cliind>-1) rooms[r].splice(cliind,1);
  32.         }
  33.         delete clients[id]
  34.     })
  35. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement