Socket IO | How to get the client transport type o

2019-02-12 13:49发布

I need to know what transport method a client is using for some conditional statements on the nodeJS serverside.

Does anyone know how I can get that information? Is it held within the client object?

7条回答
劳资没心,怎么记你
2楼-- · 2019-02-12 14:29

In socket.io 0.7.6

io.sockets.on('connection', function(client) {
    console.log(io.transports[client.id].name);
});
查看更多
一纸荒年 Trace。
3楼-- · 2019-02-12 14:29
io.connect.managers['connect url/port'].engine.transport
查看更多
再贱就再见
4楼-- · 2019-02-12 14:31

for reference's sake and google stumbles:- in case anyone is still using v0.9 (or possibly earlier) you can access this info from client side like this:

var socket = io.connect();
console.log(socket.socket.transport.name); //log the name of the transport being used.

answer found on google groups https://groups.google.com/forum/#!topic/socket_io/yx_9wJiiAg0

查看更多
冷血范
5楼-- · 2019-02-12 14:33

As of Socket.IO 1.0:

Client:

socket.on('connect', function() {
    console.log(socket.io.engine.transport.name);
}

Server:

io.sockets.on('connection', function(socket) {
    console.log(socket.conn.transport.name);
}
查看更多
萌系小妹纸
6楼-- · 2019-02-12 14:34

April 2012, this works: socket.transport

查看更多
Juvenile、少年°
7楼-- · 2019-02-12 14:35

I'm sure you can find it if you dig in the internals of a client object, although without knowing why you need this I have to recommend against this kind of check for 2 reasons:

Firstly, since it isn't in the API the developers have absolutely no responsibility to keep things backward compatible, so any given version might implement/store that information differently, which will only ripple into your own development and cause problems.

Secondly, and more importantly, I suggest you rethink your design, the communication with the server thru socket.io is built to be transparent to the method being used. There should be no difference on either side. That's the purpose of the library, designing an app that behaves otherwise is totally orthogonal to that idea.

查看更多
登录 后发表回答