Websockets basics

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the networking category.

Last Updated: 2021-05-16

The WebSocketAPI opens up a bidirectional (vs. HTTP unidirectional) communication session between the user's browser and the server - without having to poll the server. This connection is persistent - it stays open until the client or the server closes the connection.

Protocol URL

The websocket URL will look like: ws://www.google.com or the secure equivalent wss://...

Frames

There is a concept called "Frames" in ChromeTools which displays the data being transferred back and forth across the web socket channel. Often this will be lots of JSON messages which are used to update the page without AJAX or without refreshing the page.

Implementation

Uses a long-held single TCP socket connection

Example client-side code

// Create websocket object
var webSocket = new WebSocket('ws://example.com/websocketserver');

// When the socket is opened, send a string and a JSON entity
webSocket.onopen = function (event) {
  webSocket.send("Here's some text that the server is urgently awaiting!"); 
  webSocket.send(JSON.stringify(someObject));
};

// Receiving data from the server and logging it
exampleSocket.onmessage = function (event) {
  console.log(event.data);
}

Example uses

Resources