socket io tutorial - Simple Way to Emit Messages By User Id - socket io android - socket io client
Simple Way To Emit Messages By User Id
On the server:
var express = require('express');
var socketio = require('Socket io');
var app = express();
var server = http.createServer(app);
var io = socketio(server);
io.on('connect', function (socket) {
socket.on('userConnected', socket.join);
socket.on('userDisconnected', socket.leave);
});
function message (userId, event, data) {
io.sockets.to(userId).emit(event, data);
}
- Here the socket uses
connect
to check the connection and calljoin
to subscribe the given channel - Every sockets contain an uniqueid if we want to send message to an unique id then call the
userId
- And then
emit
the message for any other process within the channel - And finally
leave
from the channel
Read Also
Hello world with socket messageOn the client:
var socket = io('http://localhost:9000'); // Server endpoint
socket.on('connect', connectUser);
socket.on('message', function (data) {
console.log(data);
});
function connectUser () { // Called whenever a user signs in
var userId = ... // Retrieve userId
if (!userId) return;
socket.emit('userConnected', userId);
}
function disconnectUser () { // Called whenever a user signs out
var userId = ... // Retrieve userId
if (!userId) return;
socket.emit('userDisconnected', userId);
}
- The client emit the message to any channel randomly
Both method allows sending messages to specific users by unique id without holding a reference to all sockets on the server.