Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to emit event in socket.io based on client?

I am working on realtime data visualization application using node.js, express and socket.io.

Requirement:

Have to emit the events based on the client request.

For example: If user enter the url as http://localhost:8080/pages socket.io should emit the topic pages to client and another user request for http://localhost:8080/locations socket should emit location to that particular user.

Code

    var server = app.listen("8080");
    var socket = require('socket.io');
    var io = socket.listen(server);
    var config = {};
    io.on('connection', function (socket) {
          config.socket = io.sockets.socket(socket.id);
          socket.on('disconnect', function () {
             console.log('socket.io is disconnected');
          });
    });



    app.get('/*', function(req, res) {
      var url = req.url;
      var eventName = url.substring('/'.length);
       //pages and locations
      config.socket.volatile.emit(eventName, result);
    });

Client Code:

          //No problem in client code.Its working correctly. 
            Sample code as follows
          socket.on('pages', function (result) {
               console.log(result);
          }); 

Problem:

It is emitting pages and locations to both the clients.

Any suggestion to overcome this problem.

like image 867
karthick Avatar asked Nov 24 '22 03:11

karthick


1 Answers

I couldn't understand your approach on this, but because you said you're rendering different pages, It means you can serve different code, so what about doing it like this:

Server Side:

var server = app.listen("8080");
var socket = require('socket.io');
var io = socket.listen(server);
var config = {};

app.get('/pages', function(req, res) {
  res.render('pages.html');
});

app.get('/locations', function(req, res) {
  res.render('locations.html');
});

io.on('connection', function (socket) {
   socket.on('pagesEvent', function(data){
     socket.volatile.emit('pages', {your: 'data'});
   });
   socket.on('locationsEvent', function(data){
     socket.volatile.emit('locations', {your: 'data'});
   });
});

On Client side:

pages.html:

socket.on('connect', function(){
  socket.emit('pagesEvent', {});
});
socket.on('pages', function(data){
  // do stuff here
});

locations.html:

socket.on('connect', function(){
  socket.emit('locationsEvent', {});
});
socket.on('locations', function(data){
  // do stuff here
});
like image 196
M Omayr Avatar answered Dec 05 '22 18:12

M Omayr