There are many blogs and discussions about websocket and HTTP, and many developers and sites strongly advocate websockets, but i still can not understand why.
for example (arguments of websocket lovers):
HTML5 Web Sockets represents the next evolution of web communications—a full-duplex, bidirectional communications channel that operates through a single socket over the Web. ( http://www.websocket.org/quantum.html )
HTTP supports streaming: request body streaming(you are using it while uploading large files) and response body streaming.
During making connection with WebSocket, client and server exchange data per frame which is 2 bytes each, compared to 8 kilo bytes of http header when you do continuous polling.
Why does that 2 bytes not include tcp and under tcp protocols overhead?
GET /about.html HTTP/1.1
Host: example.org
This is ~48 bytes http header.
http chunked encoding - http://ru.wikipedia.org/wiki/Chunked_transfer_encoding :
23
This is the data in the first chunk
1A
and this is the second one
3
con
8
sequence
0
Also both protocol works over TCP, so all TCP issues with long-live connections are still there.
Question:
转载于:https://stackoverflow.com/questions/14703627/websockets-protocol-vs-http
You seem to assume that WebSocket is a replacement for HTTP. It is not. It's an extension.
The main use-case of WebSockets are Javascript applications which run in the web browser and receive real-time data from a server. Games are a good example.
Before WebSockets, the only method for Javascript applications to interact with a server was through XmlHttpRequest
. But these have a major disadvantage: The server can't send data unless the client has explicitly requested it.
But the new WebSocket feature allows the server to send data whenever it wants. This allows to implement browser-based games with a much lower latency and without having to use ugly hacks like AJAX long-polling or browser plugins.
So why not use normal HTTP with streamed requests and responses
In a comment to another answer you suggested to just stream the client request and response body asynchronously.
In fact, WebSockets are basically that. An attempt to open a WebSocket connection from the client looks like a HTTP request at first, but a special directive in the header (Upgrade: websocket) tells the server to start communicating in this asynchronous mode. First drafts of the WebSocket protocol weren't much more than that and some handshaking to ensure that the server actually understands that the client wants to communicate asynchronously. But then it was realized that proxy servers would be confused by that, because they are used to the usual request/response model of HTTP. A potential attack scenario against proxy servers was discovered. To prevent this it was necessary to make WebSocket traffic look unlike any normal HTTP traffic. That's why the masking keys were introduced in the final version of the protocol.
1) Why is the WebSockets protocol better?
WebSockets is better for situations that involve low-latency communication especially for low latency for client to server messages. For server to client data you can get fairly low latency using long-held connections and chunked transfer. However, this doesn't help with client to server latency which requires a new connection to be established for each client to server message.
Your 48 byte HTTP handshake is not realistic for real-world HTTP browser connections where there is often several kilobytes of data sent as part of the request (in both directions) including many headers and cookie data. Here is an example of a request/response to using Chrome:
Example request (2800 bytes including cookie data, 490 bytes without cookie data):
GET / HTTP/1.1
Host: www.cnn.com
Connection: keep-alive
Cache-Control: no-cache
Pragma: no-cache
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.68 Safari/537.17
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: [[[2428 byte of cookie data]]]
Example response (355 bytes):
HTTP/1.1 200 OK
Server: nginx
Date: Wed, 13 Feb 2013 18:56:27 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: keep-alive
Set-Cookie: CG=US:TX:Arlington; path=/
Last-Modified: Wed, 13 Feb 2013 18:55:22 GMT
Vary: Accept-Encoding
Cache-Control: max-age=60, private
Expires: Wed, 13 Feb 2013 18:56:54 GMT
Content-Encoding: gzip
Both HTTP and WebSockets have equivalent sized initial connection handshakes, but with a WebSocket connection the initial handshake is performed once and then small messages only have 6 bytes of overhead (2 for the header and 4 for the mask value). The latency overhead is not so much from the size of the headers, but from the logic to parse/handle/store those headers. In addition, the TCP connection setup latency is probably a bigger factor than the size or processing time for each request.
2) Why was it implemented instead of updating HTTP protocol?
There are efforts to re-engineer the HTTP protocol to achieve better performance and lower latency such as SPDY, HTTP 2.0 and QUIC. This will improve the situation for normal HTTP requests, but it is likely that WebSockets and/or WebRTC DataChannel will still have lower latency for client to server data transfer than HTTP protocol (or it will be used in a mode that looks a lot like WebSockets anyways).
Update:
Here is a framework for thinking about web protocols:
text/event-stream
MIME type. The browser API (which is fairly similar to the WebSocket API) is called the EventSource API.References:
For the TL;DR, here are 2 cents and a simpler version for your questions:
WebSockets provides these benefits over HTTP:
WebSocket and HTTP protocol have been designed to solve different problems, I.E. WebSocket was designed to improve bi-directional communication whereas HTTP was designed to be stateless, distributed using a request/response model. Other than the sharing the ports for legacy reasons (firewall/proxy penetration), there isn't much of a common ground to combine them into one protocol.
The other answers do not seem to touch on a key aspect here, and that is you make no mention of requiring supporting a web browser as a client. Most of the limitations of plain HTTP above are assuming you would be working with browser/ JS implementations.
The HTTP protocol is fully capable of full-duplex communication; it is legal to have a client perform a POST with chunked encoding transfer, and a server to return a response with a chunked-encoding body. This would remove the header overhead to just at init time.
So if all you're looking for is full-duplex, control both client and server, and are not interested in extra framing/features of websockets, then I would argue that HTTP is a simpler approach with lower latency/CPU (although the latency would really only differ in microseconds or less for either).
HTTP Polling
HTTP polling is the process of looking for the server by client in pre-defined time intervals to fetch up-to-date information if available. In HTTP polling, client send a request to a server. Then the server responds with any new messages. If there are no new messages available, the server responds with an empty or pre-agreed format. This flow is repeated by the configured polling interval. HTTP polling generates a significant network overhead in the system as it requires the repetition of the headers in each request.
Therefore, HTTP polling performs comparatively well, if the update receiving frequency is fixed. If the update receiving frequency is high or the update receipt is random or non-predictable, HTTP polling may lead to a communication overhead. Hence, the main drawback of the HTTP polling is sending number of unnecessary requests to the server even there are no new updates to fetch.
HTTP Long Polling
HTTP long polling is a variation of polling technique defined to overcome the above-mentioned drawbacks of simple polling. It is defined to efficiently handle the data transmission between the server and the client. The difference of the long polling is that, it doesn’t send an empty response immediately, when there are no new messages. Instead of that, the server waits for a new message to respond or the request is timed out. This offers more efficient solution to the polling, especially when there are less new messages in the system, reducing the number of client requests. Again, if connection timeouts are appearing beyond response, still HTTP long polling is not very advantageous. Hence, HTTP long polling has not resolved all the drawbacks appeared by HTTP polling.
WebSockets
WebSockets protocol was introduced as an extension, to enhance the client-server communication with several value additions. In real-time data exchange, WebSockets performs well with less communication overhead, providing efficient and stateful communication between client and the server. WebSockets protocol allows to maintain long term TCP socket connections between clients and servers. More importantly web sockets enable the messages to be instant delivered with a negligible overhead to the system, in real time, bi-directionally and full duplex manner. WebSockets exhibit a unique feature of traversing through firewall and proxies. It can detect the presence of proxy server and automatically sets up a tunnel to pass through the proxy. Especially the web browsers can be take the advantage of full duplex mode to send data in either direction at the same time. Also, the WebSockets provide a significant reduction of network congestion and overheads than a regular duplex system which maintain two connections with polling, by operating thought a single socket over the web.
With the enhanced capabilities of the WebSockets protocol, it is often suitable for network application frameworks to provide more of consistency, allowing massive scalability on real time platforms. Also, it has been emerging as a very reliable, highly performing, real-time ready and promising protocol for inter-node communication as well, making it a reliable methodology for cluster management.
References http://www.devdummy.com/2017/12/http-polling-http-long-polling.html
I don't think we can compare them side by side like who is better. That won't be fair comparison simply because they are solving two different problems. Their requirements are different. It will be like comparing apples to oranges. They are different.
HTTP is a request–response protocol. Client (browser) wants something, server gives it. That is. If the data client wants is big, the server might send streaming data to void unwanted buffer problems. Here main requirement or problem is how to make the request from clients and how to response the resources(hybertext) they request. That is where HTTP shine.
In HTTP, only client request. Server only responds.
WebSocket is not a request-response protocol where only the client can request. It is a socket(very similar to TCP socket). Mean once the connection is open, either side can send data until underlining TCP connection is closed. It is just like a normal socket. The only difference with TCP socket is websocket can be used in web. In web, we have much restriction for a normal socket. Most firewall will block other port than 80 and 433 that HTTP used. Proxies and intermediaries will be problematic as well.So to make the protocol more easier to deploy to existing infrastructures websocket use HTTP handshake to upgrade. That mean when the first time connection is going to open, client sent HTTP request to tell server saying "That is not HTTP request, please upgrade to websocket protocol".
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Once server understand the request and upgraded to websocket protocol, none of the HTTP protocol applied any more.
So my answer is Neither one is better than each other. They are completely different.
Well we can make everything under the name called HTTP as well. But shall we? If they are two different things, I will prefer two different names. So do Hickson and Michael Carter .