So I set up socket.io with a NodeJS + ExpressJS server and everything is working well. The only problem is I just realized that my emit()
calls are using the fallback XHR method to send the event to my server rather than the websocket connection it has open.
When I view the connection, all I see are some 2probe
, 3probe
, followed by a bunch of 2's and 3's being sent across the websocket. This connection appears to be open and working, so why is it falling back to long polling with XHR requests?
I am not providing any code right now because I am not sure what part would be relevant since the functional aspect of the code is working great, I just want to utilize the websocket over XHR. Let me know if there is any code you would like to see
UPDATE
So I was testing out the sockets a little more and I added a couple more emit()
calls. It appears like the very first 1 or 2 emits use the long polling and then all of a sudden it changes over to using the websocket. Just curious what is happening here.
First, Socket.IO creates a long-polling connection using xhr-polling. Then, once this is established, it upgrades to the best connection method available.
Long Polling usually produces slightly higher average latency and significantly higher latency variability than WebSockets. WebSockets do support compression, but usually per-message.
Although Socket.IO indeed uses WebSocket for transport when possible, it adds additional metadata to each packet. That is why a WebSocket client will not be able to successfully connect to a Socket.IO server, and a Socket.IO client will not be able to connect to a plain WebSocket server either.
Since Socket.IO 1.x, the fallback algorithm changed from a downgrade approach to an upgrade approach.
Long polling pretty much works everywhere, so that is used at first so you can get a "connection" right away. Then in the background, an attempt is made to upgrade the long polling connection to a websocket connection. If the upgrade is successful, the long polling stops and the session switches to the websocket connection. If it's not successful, the long polling "connection" stays open and continues to be used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With