What does WebSocket mean? The webpage doesn't refresh and the temperature jumps automatically. I caught a packet, and after shaking hands with this cable, it never hung up again

opened the Home Assistant page on my phone and placed it on the table, the living room temperature jumped from 26.4 to 26.5, and I didn't touch the screen. This was the thing I was most puzzled about after installing HA into the NAS last time: Isn't the webpage supposed to only move when you click? Why should it move on its own?
around the same time, I was monitoring the download speed in the qBittorrent web , and that number was also jumping, jumping one bar every two seconds. Both are 'live' pages, but I later realized that these two are implemented completely differently—one relies on repeatedly asking on the webpage, the other on the server proactively pushing it. The latter uses WebSocket.
two pages that don't refresh, one relies on asking and the other on pushing
qBittorrent That speed number uses the simplest method: polling . The script on the webpage sends a request to the server every one or two seconds—"How fast is it now?" The server replies '38.2MB/s,' disconnects the connection, and repeats every second. You see, it jumps quite fast, but actually, the webpage is refreshing every second, but each time only a small piece of data is flicked, not the entire page, so it doesn't look like a refresh.
This method may be clumsy, but it works. But the accounts need to be clear: if 100 people open this page at the same time, each asking once per second, the server will handle 100 requests per second, and most of the responses will be "same as before, no change." With more people, most of the server's computing power is spent answering 'no change.'
HA temperature isn't determined this way. A quick look at packet capture shows that after the page loads, the browser does not initiate a new request during the temperature update—the server proactively pushes down the "26.5" message. There's a premise: the connection must always be open. When the server wants to speak proactively, it must have a ready-made, undisconnected line in hand.
HTTP's rule is Q&A; the server doesn't have doors that open proactively
Thus, in December 2011, RFC 6455 established WebSocket as the standard. The idea is simple: first use the HTTP gateway to shake hands. Once the handshake is done, the TCP connection won't be dismantled, but replaced with a telephone line that can be opened at both ends at any time. It's not the same layer as the transport layer discussed in TCP and UDP's articles—WebSocket is an application layer protocol that rides on top of TCP, on par with HTTP.
Handshake: Borrowing the HTTP door to enter, never looking back after 101
just reading text wasn't enough, I set up a minimal WebSocket service on my own computer and ran through it myself using the most basic socket interface. What the client sends is actually a uniquely looking HTTP request:
GET /chat HTTP/1.1 Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: wN4C0c0BNszHE5gU96k5Xw== Sec-WebSocket-Version: 13
focus on the first two heads: Upgrade: websocket, which literally means "I want to upgrade to websocket"; Connection: Upgrade means "Don't follow the old rules on this connection." The request itself is still in HTTP format, so you exit via port 80 or 443—that's why at home these real-time pages never need to open a port on the router to forward . It's a different story from the forwarding port to allow outsiders to connect: the connection is initiated by the home and the direction is reversed. port numbers still the same old ports, the router treats them as ordinary web traffic.
If you know
server, you can reply like this:
HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: 7pBSP80/MOKV55KufDiJMIOhP/o=
most puzzling handshake is the pair Key and Accept. Sec-WebSocket-Key is a base64 generated by the client with 16 random bytes on site. This time, I caught wN4C0c0BNszHE5gU96k5Xw==, and each connection is different. The server gets it, puts a string of characters written in the protocol at the back of the butt: 258EAFA5-E914-47DA-95CA-C5AB0DC85B11, performs SHA-1 as a whole, then bases 64 to get Accept and returns it to you.
I manually calculated this step, and the server gave me the accept, which is exactly one byte different. Note that this is not encryption—the string is public, and anyone can count it. Its purpose is written in the RFC: to prevent old proxy servers on the street from caching upgrade requests as ordinary HTTP responses and causing trouble, and to confirm that the other side truly understands WebSocket, not just a misled ordinary HTTP service. Simply put, it's a code signal, not an anti-eavesdropping device. If you really want to keep it confidential, use wss to install WebSocket into TLS and run it, just like with https.
after connecting, what he said wasn't human speech—it was frame
after the handshake, the data for both hairs on this line is called 'frames.' I had the client send a message saying "Home temperature 26.5" over there, and the server replied after receiving it. Breaking it apart, the first two bytes of the frame are the status bits: FIN (is this the last frame of the entire message) and opcode (what type of the frame is). The commonly used opcodes are just a few
| opcode | frame type | What is it used for |
| 0x1 | text frame | JSON message, The most common |
| 0x2 | binary frames | images and audio, such as bare data |
| 0x8 | turn off frames | politely say goodbye, don't just unplug the cord directly |
| 0x9 | ping | Are you still here |
| 0xA | pong | in |
there's an interesting rule: every frame sent by client to the server must be masked—the text must have 4 random bytes as keys, and the content is XOR with each byte. The server either receives it or restores it. Frames sent by the server to the client are not allowed to be masked, effectively exposing the frames. The RFC gives the reason to prevent caching poisoning by middlemans. In my experiment, the phrase "home temperature 26.5" was rewritten by 4 bytes, and the server only recognized it after unlocking it.
ping and pong are the heartbeats that come with the protocol. The troublesome part is that JavaScript in the browser can't send protocol ping at the protocol level; it has to rely on the web page sending a small JSON at the application layer, like {"type":"ping"}, and the other party replies with a single one, every twenty to thirty seconds. Why must it be heartbeat? Read on.
Why does this cable quietly die as soon as the phone locks the screen
phone lock screen is even more ruthless: the system directly cuts off the wireless, and the TCP connection physically dies. After unlocking, the webpage script detects a heartbeat timeout, reconnects, reshakes hands, and resubscribes—this entire fault tolerance is written by each real-time webpage itself, ignored by the protocol. That's why, when unlocking the phone and returning to the HA page, you occasionally see all the numbers flashing and refreshing once as soon as it reconnects. In the from HTTP/3, QUIC's connection migration can save the network from disconnection, but the mainstream WebSocket implementation still relies on the old TCP. When phones switch from WiFi to traffic, this line is basically broken and reconnected.
who at home uses it, how could they see it with their own eyes
casually checked the area; quite a few families rely on this line:
| scenario | What do you use it for | |
| HA The official documentation states that the frontend is fully implemented /api/websocket, and the device status changes proactively to push | ||
| view the surveillance footage in the browser | the video data is pushed through via binary frames. See the real-time link in the remote inspection monitoring | |
| web version chat, online customer service | new message server pops up directly | |
| qBittorrent Download page | counterexample: Honest polling, one question per second |
want to see it in person, it's not hard to see it in person. the same entry point as checking cache: press F12 in your browser to open Developer Tools, and in the Network panel, there's a filter called WS, dedicated to WebSocket connections. Open the HA page and click in, you'll see a connection with status 101 hanging there; Then click the Messages or Frames tab, and when the temperature updates, small messages pop up, all pushed by the server, and the browser hasn't sent a single request. If the WS column is empty and a small batch of requests appear every second in the Network list, then the page is polling and has nothing to do with WebSocket.
to conclude: Q&A is HTTP's duty, and after 101, talking freely between both ends is WebSocket's privilege. Next time you see numbers on the webpage jumping on their own, press F12 first to tell if it's asking or pushing—the asking one watches the server's mood, the push is the real line that won't hang up.
