Node.js era qualcosa a cui ero davvero interessato e l'ho usato in uno dei miei progetti per creare un gioco multiplayer.
io.sockets.in().emit()
e socket.broadcast.to().emit()
sono i due principali metodi di emissione che utilizziamo nelle stanze di Socket.io ( https://github.com/LearnBoost/socket.io/wiki/Rooms ) Le stanze consentono un semplice partizionamento dei client connessi. Ciò consente di emettere eventi con i sottoinsiemi dell'elenco dei client connessi e fornisce un metodo semplice per gestirli.
Ci permettono di gestire i sottoinsiemi della lista dei clienti collegati (che chiamiamo stanze) e hanno funzionalità simili come le funzioni principali di socket.io io.sockets.emit()
e socket.broadcast.emit()
.
Comunque cercherò di fornire i codici di esempio con i commenti per spiegare. Vedi se aiuta;
Socket.io Rooms
i) io.sockets.in (). emit ();
/* Send message to the room1. It broadcasts the data to all
the socket clients which are connected to the room1 */
io.sockets.in('room1').emit('function', {foo:bar});
ii) socket.broadcast.to (). emit ();
io.sockets.on('connection', function (socket) {
socket.on('function', function(data){
/* Broadcast to room1 except the sender. In other word,
It broadcast all the socket clients which are connected
to the room1 except the sender */
socket.broadcast.to('room1').emit('function', {foo:bar});
}
}
Socket.io
i) io.sockets.emit ();
/* Send message to all. It broadcasts the data to all
the socket clients which are connected to the server; */
io.sockets.emit('function', {foo:bar});
ii) socket.broadcast.emit ();
io.sockets.on('connection', function (socket) {
socket.on('function', function(data){
// Broadcast to all the socket clients except the sender
socket.broadcast.emit('function', {foo:bar});
}
}
Saluti