ForceUser
ForceUser

Reputation: 1119

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

Upvotes: 5

Views: 2756

Answers (1)

ricardopereira
ricardopereira

Reputation: 11683

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

Upvotes: 8

Related Questions