How Websockets are implemented?

前端 未结 2 754
执笔经年
执笔经年 2020-12-13 03:00
  • How Websockets are implemented?
  • What is the algorithm behind this new tech (in comparison to Long-Polling)?
  • How can they be better than Long-Polling
2条回答
  •  执念已碎
    2020-12-13 03:37

    Very good explanation about web sockets, long polling and other approaches:

    In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?

    Long poll - request → wait → response. Creates connection to server like AJAX does, but keep-alive connection open for some time (not long though), during connection open client can receive data from server. Client have to reconnect periodically after connection is closed due to timeouts or data eof. On server side it is still treated like HTTP request same as AJAX, except the answer on request will happen now or some time in the future defined by application logic. Supported in all major browsers.

    WebSockets - client ↔ server. Create TCP connection to server, and keep it as long as needed. Server or client can easily close it. Client goes through HTTP compatible handshake process, if it succeeds, then server and client can exchange data both directions at any time. It is very efficient if application requires frequent data exchange in both ways. WebSockets do have data framing that includes masking for each message sent from client to server so data is simply encrypted. support chart (very good)

    Overall, sockets have much better performance than long polling and you should use them instead of long polling.

提交回复
热议问题