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 call join 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

On 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.



Related Searches to Simple Way to Emit Messages By User Id

Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add wikitechy.com to your ad blocking whitelist or disable your adblocking software.

×