Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get event details in middleware for socket.io

I am trying to log the event name and parameter for each event on my Node server. For this purpose I used

io.use(function(socket, next){
  // how to get event name out of socket.
});

Now, I got stuck while trying to get event name and arguments. To me, it looks like common demand from API dev, so I am pretty sure there must be some way to the library to get that, I have tried to read the docs and source but I am not able to get the stuff.

like image 709
Gaurav Gupta Avatar asked Oct 01 '15 08:10

Gaurav Gupta


People also ask

How do I check if a message sent through Socket.IO is read?

You will have to send a message back when the message is read. There is no notion of when something is "read" in socket.io. That's something you would have to invent in your own user interface and when you consider it read, you could send a message back to the sender that indicates it is now read.

What is the difference between Socket.IO and socket IO client?

socket-io. client is the code for the client-side implementation of socket.io. That code may be used either by a browser client or by a server process that is initiating a socket.io connection to some other server (thus playing the client-side role in a socket.io connection).

Does Socket.IO use long polling?

js) and the Socket.IO client (browser, Node. js, or another programming language) is established with a WebSocket connection whenever possible, and will use HTTP long-polling as fallback.

How many Socket.IO connections can a server handle?

Once you reboot your machine, you will now be able to happily go to 55k concurrent connections (per incoming IP).


1 Answers

The socket events needs to be handled properly,in any case if an event is not handled there will be no response.

var io = require('socket.io')(server);
var sessionMiddleWare=(session({secret: 'secret key', resave: true, saveUninitialized: true,cookie: { path: '/', httpOnly: true, maxAge: 300000 },rolling: true}));

app.use(sessionMiddleWare)

io.use(function(socket, next) {
  sessionMiddleWare(socket.request, socket.request.res, next);
});

io.on('connection', function(socket) {  // On Socket connection.
   // inside this you can use different events

   //event name and parameters can be found in socket variable.

   console.log(socket.id) // prints the id sent from the client.
   console.log(socket.data) // prints the data sent from the client.

   // example event

   socket.on('subscribe', function(room) {  // Event sample.
        console.log('joining room', room);
        socket.room=room;
        socket.join(room);
    });
})

Hope this helps.

like image 61
SUNDARRAJAN K Avatar answered Sep 22 '22 17:09

SUNDARRAJAN K