Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect when socket.io transport changes? (event or something)

I'm trying to connect to server io.js+socket.io with socket.io client. It starts with xhr polling requests, the connect event and even first message are receiving throught xhr, then it upgrades to websocket. How can i detect when the switch of the transport happens to log it (on both sides)?

Simplified server code:

io.on("connection",function(socket){
    console.log("transport",socket.conn.transport.name); //will print "polling"
    socket.on("join",function(data){
        console.log("transport",socket.conn.transport.name); //will print "polling" (usualy)
        console.log("userjoined",data.userInfo);
    });
    socket.on("testMsg",function(data){
        console.log("transport",socket.conn.transport.name); //will print "websocket" (if it supported and already switched)
    });
    socket.emit("hello","hello");
})

Simplified client code:

var socket = io.connect();
socket.on("hello",function(data){
    socket.emit("join",{userInfo: {name:"someName"}});
    setTimeout(function(){
        socket.emit("testMsg",{}); 
    },8000)
});
like image 740
ForceUser Avatar asked Feb 19 '15 16:02

ForceUser


People also ask

How do I monitor Socket.IO traffic?

Use Monitor.io to observe connections and replay messages It shows a list of active Socket.io client connections for your application. You can use the monitoring interface to broadcast messages–either globally or to a specific client.

How do you check if socket IO client is connected or not?

You can check the socket. connected property: var socket = io. connect(); console.

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.

Does Socket.IO auto reconnect?

In the first case, the Socket will automatically try to reconnect, after a given delay.


1 Answers

Client Side

You can catch changes with:

<script>
  var socket = io();

  /* Transport */
  socket.io.engine.on('upgrade', function(transport) {
    console.log('transport changed');
  });
</script>

Server Side

You can catch changes with:

io.on('connection', function(socket) {
  console.log('User connected')

  // Transport event
  socket.conn.on('upgrade', function(transport) {
      console.log('transport changed')
  })
})
like image 190
ricardopereira Avatar answered Oct 05 '22 08:10

ricardopereira