Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //WebSocket multipurpose chatserver
- //how it works: retransmits the message to all members of the current room
- //message packet format: stingified JSON with mandatory roomid field
- //other fields can be arbitrary data
- var WebSocketServer = new require('ws');
- var webSocketServer = new WebSocketServer.Server({port: 8081});
- var clients = {}, rooms = {};
- webSocketServer.on('connection', function(ws) {
- var id = Math.ceil(Math.random()*(1<<30));
- clients[id] = ws;
- ws.on('message', function(rawmsg) {
- try{
- var packet = JSON.parse(rawmsg);
- if('roomid' in packet) {
- var roomid = packet.roomid;
- if(!(roomid in rooms))rooms[roomid]=[];
- if(rooms[roomid].indexOf(clients[id])==-1) rooms[roomid].push(clients[id]);
- for(var c in rooms[roomid]){
- var cli = rooms[roomid][c];
- if(cli!=clients[id]) cli.send(rawmsg)
- }
- }
- }
- catch(err){}
- });
- ws.on('close', function(){
- for(var r in rooms) {
- var cliind = rooms[r].indexOf(clients[id]);
- if(cliind>-1) rooms[r].splice(cliind,1);
- }
- delete clients[id]
- })
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement