Created
March 20, 2014 12:29
-
-
Save Hagith/9662700 to your computer and use it in GitHub Desktop.
Simple Socket.io server for chat-like communication.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "Socket", | |
"description": "Simple Socket.io server for chat-like communication.", | |
"version": "0.1.0", | |
"main": "server.js", | |
"dependencies": { | |
"socket.io": "~0.9.16" | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var app = require('http').createServer(function (req, res) {}), | |
io = require('socket.io').listen(app); | |
app.listen(8080); | |
var getRoomClients = function (room) { | |
var clients = []; | |
io.sockets.clients(room).forEach(function (client) { | |
clients.push({node: client.id, user: client.user}); | |
}); | |
return clients; | |
}; | |
io.sockets.on('connection', function (socket) { | |
socket.on('room-join', function(room, user) { | |
socket.join(room); | |
socket.user = user; | |
var clients = getRoomClients(room); | |
// confirm join to sender | |
socket.emit('join', clients); | |
// sending to all clients in room except sender | |
socket.broadcast.to(room).emit('joined', room, socket.id, user, clients); | |
}); | |
socket.on('room-leave', function(room) { | |
socket.leave(room); | |
var clients = getRoomClients(room); | |
// sending to all clients in room except sender | |
socket.broadcast.to(room).emit('left', room, socket.id, socket.user, clients); | |
}); | |
socket.on('room-data', function (room, data, dataType, id) { | |
if (id) { | |
io.sockets.socket(id).emit('data', room, socket.id, data, dataType); | |
} else { | |
socket.broadcast.to(room).emit('data', room, socket.id, data, dataType); | |
} | |
}); | |
socket.on('disconnect', function () { | |
// leave all rooms a client was joined | |
var rooms = io.sockets.manager.roomClients[socket.id]; | |
for (var room in rooms) { | |
if (room !== '' && rooms[room]) { | |
room = room.slice(1); | |
socket.leave(room); | |
// send to all clients in room except sender | |
socket.broadcast.to(room).emit('left', room, socket.id, socket.user, getRoomClients(room)); | |
} | |
} | |
// send to current request socket client | |
socket.emit('disconnect'); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment