Instant browser refresh with a WebSocket connection
Programming Snapshot – WebSockets

© Photo by Micah Tindell on Unsplash
The WebSocket protocol helps browsers to immediately reload a page if the server-side content changes. In this month's column, Mike Schilli whips up his own WebSocket server in Go for this task.
You may have wondered what kind of magic it takes for, say, a WhatsApp or Slack chat open in your web browser to respond so quickly to new input from your chat partner, or to show that your partner is typing … even before the message has been sent (Figure 1)? To do that, the browser at least needs to partially reload the page you are viewing, but how does it know when to do so?
In the simplest of cases, the browser could just periodically ask the server, but that would generate unnecessary network traffic – after all, nothing would have changed most of the time. This also would cause periodic flickering of what was a largely static page, which would look pretty unprofessional. For a better approach, you could turn the setup on its head and only wake up the browser if the file has changed at the server end.
Unlike with the HTTP protocol, the browser will no longer send a request that the server then responds to before closing the connection. Instead, the browser uses the WebSocket protocol to open a persistent connection to a special server. As soon as it is opened, both the server and the client can send messages to each other, available immediately to the receiver at the other side of the open channel. In other words, the two parties actively listen on their ends and react whenever new information arrives.
[...]
Buy this article as PDF
(incl. VAT)