如何检测socket.io传输何时更改? (事件或其他)

时间:2015-02-19 16:14:16

标签: javascript socket.io

我尝试使用socket.io客户端连接到服务器io.js + socket.io。它以xhr轮询请求开始,连接事件甚至第一条消息都通过xhr接收,然后升级到websocket。如何检测传输开关何时记录(两侧)?

简化的服务器代码:

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

简化的客户端代码:

var socket = io.connect();
socket.on("hello",function(data){
    socket.emit("join",{userInfo: {name:"someName"}});
    setTimeout(function(){
        socket.emit("testMsg",{}); 
    },8000)
});

1 个答案:

答案 0 :(得分:7)

客户端

您可以通过以下方式捕捉更改:

<script>
  var socket = io();

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

服务器端

您可以通过以下方式捕捉更改:

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

  // Transport event
  socket.conn.on('upgrade', function(transport) {
      console.log('transport changed')
  })
})