Do websocket implementations use http protocol internally?
Yes, initially, then they switch to the webSocket protocol. All webSocket connections start with an HTTP request with a header that requests an upgrade to the webSocket protocol. If the receiving server agrees, then the two sides switch protocols from HTTP to webSocket and from then on the connection uses the webSocket protocol.
So, ALL webSocket servers MUST support that initial HTTP request because that's how all webSocket connections are started.
The webSocket protocol is designed this way for a couple reasons:
So a single host and port can be used for both regular HTTP and webSocket connections. If you want, you can use a single server process to handle both types of connections. If they were on different ports, you would need two separate server processes.
So that webSockets can run on port 80 or 443 (along with an HTTP server) for maximum compatibility with various, already deployed network infrastructure such as corporate proxies, firewalls, etc.... that may only permit traffic on regular HTTP ports.
As you've seen, a webSocket request starts with an HTTP request like this:
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://example.com
Note the Upgrade: websocket
header. That tells the receiving HTTP server that this is a request for a webSocket connection. If the server wants to accept that connection, it returns a 101 response which tells the client that they can now switch protocols:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat
After this response, both client and server switch protocols (on the same TCP connection) and from then on they only speak the webSocket protocol and the TCP connection remains open until client or server explicitly close it (typically a long lived connection).
I can't understand it. To initialize the connection HTTP GET request is sent. But what if I don't host HTTP server but I just host WebSocket server?
All webSocket servers have to accept HTTP requests because all webSocket connections start with an HTTP request. So, there is no such thing as a webSocket server that doesn't accept an HTTP request. A pure webSocket only server can only accept HTTP requests that have the Upgrade: webSocket
header and fail any other HTTP requests.
How does it handle HTTP requests then?
All webSocket servers expect incoming, new connections to start with HTTP so they must have a simple HTTP server built-in (can parse the initial HTTP headers).