I am trying to learn Socket.io by creating a set of dynamically created chats that come out of “connected” and “disconnected” messages when users log in and out. After looking at a couple of questions, I put together something functional, but most of the answer is related to people who admit that they have cracked the answers, and I noticed there is a more general and recent discussion about the correct way to do this on Socket. io repo (especially here and here )
Since I'm such a newbie, I don’t know if the work below is an acceptable way to do something or just happens by accident, but it will cause performance problems or lead to too many listeners. If there is an ideal and formal way to join in and leave rooms that feel less awkward than that, I would love to know about it.
Client
var roomId = ChatRoomData._id
function init() {
if (!Socket.socket) {
Socket.connect();
}
Socket.on('connect', function() {
Socket.emit('room', roomId);
});
$scope.$on('$destroy', function () {
Socket.removeListener('connect');
});
}
init();
Server
io.sockets.once('connection', function(socket){
socket.on('room', function(room){
socket.join(room)
io.sockets.in(room).emit('message', {
type: 'status',
text: 'Is now connected',
created: Date.now(),
username: socket.request.user.username
});
socket.on('disconnect', function () {
io.sockets.in(room).emit({
type: 'status',
text: 'disconnected',
created: Date.now(),
username: socket.request.user.username
});
})
});
source
share