javascript - Using rooms with socket.io -
in socket.io
documentation see example of rooms
io.on('connection', function(socket){ socket.on('say someone', function(id, msg){ socket.broadcast.to(id).emit('my message', msg); }); });
i have route /rooms/:roomid
.
is possible make sockets being sent between server , client hits specific room?
i guess server should like
io.on('connection', function(socket){ socket.on('new msg client', function(roomid, msg){ io.to(id).emit('new msg server', msg); }); });
above , client should send messages with
socket.emit('new msg client', roomid, msg);
and new messages with
socket.on('new msg server', function () { document.getelementbyid('msgs').appendchild(...); });
but work? shouldn't join room socket.join(...)
before can this?
for haiku sharing application made have this:
io.on('connection', function(socket) { var socket_id = socket.id; var client_ip = socket.handshake.headers['x-forwarded-for'] || socket.handshake.address.address; clients.push(socket); console.info('new client connected (id=' + socket.id + ').'); number_of_clients_connected++; console.log('[' + client_ip + '] connected, ' + number_of_clients_connected + ' total users online.'); //when socket disconnected or closed, .on('disconnect') fired socket.on('disconnect', function() { number_of_clients_connected--; console.log('[' + client_ip + '] disconnected, ' + number_of_clients_connected + ' total users online.'); //on disconnect, remove clients array var index = clients.indexof(socket); if (index != -1) { clients.splice(index, 1); //console.info('client gone (id=' + socket.id + ').'); } });
so keeps array of clients , when messages need relaying can specify client socket id...
//reads latest_haikus_cache , sends them socket.on('request_haiku_cache', function() { latest_haikus_cache.foreach(function(a_latest_haiku) { clients[clients.indexof(socket)].emit('load_haiku_from_cache', a_latest_haiku); }); });
Comments
Post a Comment