Web sockets
Contents

Why they matter for APIs

Web sockets are important for APIs because they allow servers to send data to your application instantly, and your application can send updates back just as quickly. This avoids the constant opening and closing of connections that traditional HTTP requests do, which cuts down on delays and reduces wasted internet data. This is especially useful whenever you need information updated in real-time.

How web sockets work under the bonnet

Handshake to upgrade HTTP to web socket

The process starts just like any normal HTTP request. The client sends a specially formatted GET request asking the server to change communication methods. This request includes key headers such as:
Upgrade: websocket – this shows it’s a request to change the protocol.
Connection: Upgrade – this tells any intermediate network devices to allow the change.
Sec-WebSocket-Key – a random, encoded value that the server uses to create a response key.
Sec-WebSocket-Version – this states the version of the web socket protocol the client supports.

The server then replies with an HTTP 101 Switching Protocols response, and includes headers like:
– Upgrade: websocket and Connection: Upgrade.
– Sec-WebSocket-Accept – a unique code based on the client’s key, proving the server supports web sockets.

Once this initial exchange is complete, the connection officially switches to web socket mode.

Persistent two-way connection

After the handshake, the connection remains open over TCP. Data can flow in both directions at any time with very little overhead. Unlike HTTP polling, each message doesn’t need a new connection to be set up. This makes communication fast and efficient for real-time interactions.

Framing messages for delivery

Once connected, data is sent using “frames”—small packets that carry the message. These frames include:
– An Opcode to show the type of frame (e.g., text, binary, ping, close).
– Masking (used by the client to hide data from proxy servers).
– The Payload, which contains the actual message.

Frames allow web sockets to support messages split into multiple parts, and also control signals like ping/pong (to keep the connection alive) or close frames when ending a session.

Why handshake matters

The handshake achieves two important things:
– It reuses the same network ports and server setup used for standard HTTP (usually port 80 or 443). This means web socket traffic blends in with normal web traffic and can pass through firewalls easily.
– It enforces security checks, such as verifying the origin of the connection, which helps prevent web socket hijacking or unwanted connections from other websites.

Web socket API interface (client-side)

How to open a connection

To start using web sockets in JavaScript, you create a WebSocket object, providing the server’s URL.

const socket = new WebSocket("wss://example.com/socket", "protocolOne");

The second part, “protocolOne”, is optional and lets you suggest a sub-protocol (like JSON or a custom format); this is agreed upon with the server.

This line immediately tries to open the connection. You can check its progress using the readyState property: 0 means it’s connecting, 1 means it’s open, and 3 means it’s closed.

Key events and methods

Once the connection is open and running, you can react to specific events and send data:
Onopen: This triggers when the connection is ready. It’s a good place to send your first message reliably.
– Onmessage: This fires when the server sends data. The received data is found in event.data (you’d use JSON.parse if the server is sending structured data).
Onerror: This fires if something goes wrong, such as the connection failing or a protocol error.
Onclose: This fires when the connection officially closes, whether initiated by your code or the server. It can optionally include a close code and a reason message.

The main methods you’ll typically use are:
Send(): Use this to send a message to the server. It supports various data types like strings, binary data, Blob, or ArrayBuffer. Important: Only send messages after the connection is open, otherwise it might fail.
Close(): Use this to shut down the web socket connection. You can also provide an optional code and reason. This starts a closing “handshake,” and any messages still waiting to be sent will go first before the connection fully closes.

Sample client-side code flow

const socket = new WebSocket("wss://example.com/socket");

socket.onopen = (event) => {
  socket.send(JSON.stringify({ type: "subscribe", channel: "updates" }));
};

socket.onmessage = (event) => {
  console.log("Received:", event.data);
};

socket.onerror = (event) => {
  console.error("Web socket error", event);
};

socket.onclose = (event) => {
  console.log("Socket closed", event.code, event.reason);
};

How it works

– You connect using new WebSocket(…).
– You wait for the onopen event before sending any data.
– You listen to the onmessage event for any incoming data from the server.
– You handle any problems in the onerror event.
– You clean up the connection in the onclose event.

Common use cases and benefits

Common use cases

Web socket APIs are perfect when you need fast, real-time updates. Typical applications include:
– Live chat and messaging systems, where messages appear instantly for all users.
– Online multiplayer games, which rely on immediate gameplay updates.
– Collaborative editing tools (e.g., shared documents, whiteboards) with real-time syncing.
– Live sports scores, financial tickers, and dashboards that update as events happen.
– IoT (internet of things) and device monitoring applications, for real-time sensor data or control messages.
– Notification systems or alert feeds pushing updates to clients instantly.

Benefits compared to polling or REST

Using web sockets offers several real advantages over traditional methods like HTTP polling or standard REST APIs:
Lower latency: Messages travel instantly once the connection is open, without waiting for a request-response cycle. This avoids artificial delays common in polling.
Reduced bandwidth and server load: Since the connection stays open, there’s no repeated overhead from HTTP headers or reconnections. That lowers the amount of internet data used and resources consumed on both the client and server.
True two-way communication: Web sockets support full-duplex messaging, meaning the client and server can send messages to each other at any time. This makes interactions more natural and responsive.
Efficient at scale: With the right infrastructure, web socket servers can manage thousands or even millions of simultaneous connections, making them suitable for large-scale real-time applications.

Considerations and best practices

Use secure connection (wss://) in production

Always run web sockets over TLS encrypted channels (wss://) to keep data safe while it’s being sent. Use trusted security certificates and check where clients are connecting from to prevent unauthorised access. Using token-based authentication (like JWTs) is recommended instead of relying on cookies or insecure headers.

Implement error handling and reconnect logic

Add code to handle onerror and onclose events. This helps you spot problems like network failures or unexpected server disconnections. Give users feedback when there are connection issues, and build strong reconnection logic. Use “exponential back-off” (waiting longer and longer between retry attempts) with optional “jitter” (a small random delay) to avoid overwhelming the server.

Tune heartbeat and keep-alive mechanisms

Use ping/pong frames or regular “heartbeat” messages to check if connections are still active. If no response comes back within a set time, close the connection and try to reconnect. Setting the interval correctly prevents unnecessary disconnections and avoids extra network traffic.

Plan for scalability and connection management

Design your backend system to support many web socket clients at the same time. Consider:
– Load balancing across multiple servers (using “sticky sessions” if required, to ensure a client always connects to the same server).
– Grouping application servers together and using tools like Redis or “publish/subscribe” message brokers to share information across them.
– Pooling connections and changing the size of these pools automatically during busy periods.

Optimise performance and resource use

Use small, compact data formats (like binary, minified JSON, or MessagePack) to reduce the size of messages. Close connections for clients that are idle or slow to free up resources. Limit the size of messages and the rate at which each client can send messages to prevent overload or misuse.

Monitor and log connection health

Track important numbers like the number of connections, errors, message rates, and delays. Use Application Performance Monitoring (APM) tools (like New Relic or DataDog) or set up custom logging. Analyse errors early to prevent wider failures and improve reliability.

Get started with the Sportmonks football API today

Ready to bring your sports applications to life with real-time, comprehensive football data? The Sportmonks Football API offers everything you need i.e. live scores, fixtures, player stats, and more, all accessible through simple, well-documented endpoints. Whether you’re building a fan app, a betting platform, or a fantasy football tool, our API empowers you to create innovative solutions with ease. Sign up for a free trial now and start exploring our rich dataset.

Faqs about web sockets

What are common use cases for web sockets?
Common use cases include live chat and messaging systems, online multiplayer games, collaborative editing tools, live sports scores, and IoT applications.
How do you implement web sockets in JavaScript?
You can implement web sockets in JavaScript using the web socket object, handling events like onopen, onmessage, onerror, and onclose.
What are some best practices for using web sockets?
Best practices include using secure connections (wss://), implementing error handling and reconnect logic, tuning heartbeat and keep-alive mechanisms, and planning for scalability and connection management.
How can web sockets improve real-time applications?
Web sockets can improve real-time applications by providing instant updates, reducing latency, and enabling efficient communication between clients and servers.

Written by David Jaja

David Jaja is a technical content manager at Sportmonks, where he makes complex football data easier to understand for developers and businesses. With a background in frontend development and technical writing, he helps bridge the gap between technology and sports data. Through clear, insightful content, he ensures Sportmonks' APIs are accessible and easy to use, empowering developers to build standout football applications