0

when I read engine io protocol, I found it use polling to establish the connection and then upgrade the transport to websocket, I don't know why ? could you give me some idea?

monokeros
  • 21
  • 2

3 Answers3

0

It's because the WebSocket upgrade could fail, so having polling as a fallback mechanism is useful.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • If the clientside support ws,it can use ws transport .why it "first" use polling although the client side has already supported ws? – monokeros Jan 15 '15 at 03:32
  • Because the network may not support WS, e.g. a firewall could block it. This is a fairly common occurrence. – John Zwinck Jan 15 '15 at 03:33
0

It doesn't really use polling. The initial HTTP url may look like it's a setup for polling, but that will go into play only if the server doesn't agree to upgrade the connection to the webSocket protocol.

A socket.io connection starts with a single TCP connection which is an HTTP request with certain webSocket headers set and then when the server responds that the webSocket protocol is supported, the connection is "upgraded" from HTTP to webSocket and both sides switch the protocol being used from HTTP to webSocket. This is how the webSocket protocol is specified.

If the client/server combination does not support webSocket, then and only then does socket.io resort to using long polling.

This particular design allows both webSocket and HTTP to share the same port and the socket.io design allows for a graceful fallback to long-polling if both sides don't agree on a webSocket upgrade.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

engine.io/socket.io 1.x+ starts with polling first because that pretty much always works with all types of clients, allowing them to get connected very quickly. Then in the background, attempts to upgrade the connection are made (to WebSockets or whatever else). That way if the connection upgrades fail, nothing is lost because the polling is still working like before, so there is no down time.

The reason for this change from the old behavior of downgrading instead of upgrading is that WebSockets can be troublesome to get going correctly in some situations (e.g. problems with load balancers, proxies, etc.) and even if they do get connected there can be some extra delays involved. Also using the flash fallback for WebSockets would take some time to get connected because it involves extra roundtrips and some additional delays.

mscdex
  • 104,356
  • 15
  • 192
  • 153