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

I am working on a real-time data visualization application using node.js, express and socket.io.

Requirements:

It is necessary to generate events based on a client request.

Eg . If the user enters url as http://localhost:8080/pages, socket.io should give the topic to the pagesclient, and another user request for http://localhost:8080/locationssocket should emit a locationspecific user.

The 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 emits pagesand locationsfor both clients.

Any suggestion to solve this problem.

+3
source share
2 answers

, , , . , , :

:

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'});
   });
});

:

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
});
+1

, WebSockets . , /.

, -, API, - WebSockets XHR.

-1

All Articles