websocket, http or both?

2019-08-29 09:34发布

问题:

Writing a one page web application, and knowing that some of the screens would need real-time updates, I am faced to one big general question, whatever API and frontend framework and language I am going to use:

I'll implement data transfer over websocket, should I keep http for any data transfer which would not need real-time updates, or should I just use websocket?

Knowing that websockets are not handled on ALL browsers but most if not all recent ones support it, would it be better for the servers to handle both websocket and http, or should I just use websockets for ALL data transfer?

回答1:

You will probably end up using both WebSockets and HTTP requests at the end.

WebSockets, because it sounds like you need them (because of the real-time updates) and can afford to require browser support for them (otherwise, you'd be forced to use the older Ajax/Comet based approaches).

HTTP for two possible reasons:

  • You will sooner or later need a blocking request-response behavior. For example, authenticating a user may need to block for the result before further processing happens, so you need to send a request for authentication and block until you get the result. This can be a bit annoying to handle over WebSockets.
  • You may need to load heavy data without interrupting the ongoing real-time updates. If you were to load such data over WebSockets (as a single big chunk), it will be queued together with the real-time updates and may delay them.

Both of these issues can be handled over WebSockets, but they are simply easier to solve with simple HTTP Ajax requests.



回答2:

Use websockets for the following needs,

  1. Server data changes frequently
  2. Multi-user communication
  3. Live feeds etc.,

Refer this for better understanding on websocket usage.



标签: sockets http web