我尝试使用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)
});
答案 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')
})
})