
WebSockets are a game-changer for real-time communication between a client and a server. They allow for bidirectional, full-duplex communication over the web, enabling features like live updates, chat applications, and collaborative editing.
To establish a WebSocket connection, a client sends a WebSocket handshake request to the server, which includes the "Upgrade" header. This request is typically sent over HTTP, but it's not a regular HTTP request.
The server responds with a WebSocket handshake response, which also includes the "Upgrade" header. If the handshake is successful, the connection is upgraded to a WebSocket connection.
WebSockets are particularly useful for applications that require real-time updates, such as live scores, stock prices, or chat logs.
Additional reading: Websocket Client in Java
What You Will Create
You'll create a real-time communication system that allows for bidirectional communication between a client and a server. This system will enable efficient data exchange and updates.
You'll build a server that accepts a message carrying a user's name and responds with a greeting pushed into a queue to which the client is subscribed. This queue will enable the client to receive updates in real-time.
If this caught your attention, see: Client Websocket C#
The system will utilize websockets, a technology that allows for bi-directional, real-time communication between a client and a server. This will enable seamless updates and interactions.
As you build this system, you'll work with websockets to establish a connection between the client and server, enabling the exchange of messages and updates. This connection will be maintained throughout the interaction.
Check this out: Websocket Create Connection
Prerequisites
Before diving into this websocket tutorial, make sure you have a solid foundation in Python and JavaScript.
This tutorial assumes you're comfortable with the basics of these programming languages. If you're not, don't worry - websockets is a lightweight library that doesn't require any dependencies, so you can still follow along without any issues.
To confirm, you can check if websockets is installed by running a command. If you've installed a different version, you should switch to the corresponding version of this documentation.
Make sure the HTTP server and the WebSocket server are still running. If you've stopped them, you can start them again with a simple command.
Consider reading: Websockets vs Sse
Create Controller
To create a controller for handling messages in a Spring-based WebSocket application, you'll need to annotate a class with @Controller. This is demonstrated in the GreetingController example, where the controller is mapped to handle messages to the /hello destination.
The @MessageMapping annotation is used to ensure that the greeting() method is called when a message is sent to the /hello destination. This annotation is crucial for mapping the message to the correct method.
In the GreetingController, the payload of the message is bound to a HelloMessage object, which is passed into the greeting() method. This allows the method to access the message's payload and process it accordingly.
C#
C# is a versatile language that allows you to create a WebSocket client using its ClientWebSocket class.
You can connect to a WebSocket server at a URL like wss://my-websocket-server.com using this class.
The ClientWebSocket class is part of the System.NET.WebSockets namespace, making it easy to integrate into your project.
Once connected, your C# WebSocket client can listen for messages and display them on the console.
It can also send a reply back to the server, making it a powerful tool for real-time communication.
JavaScript
JavaScript is a great language for client-side web development, and it's widely adopted too. It natively supports the WebSocket API, making it straightforward to create a WebSocket client in JavaScript/HTML.
You can build a server that accepts a message carrying a user's name, and in response, it will push a greeting into a queue to which the client is subscribed. This is a fundamental concept in creating a controller.
JavaScript's WebSocket client is particularly useful for real-time communication, allowing you to push messages to clients instantly.
Recommended read: Websocket in Javascript Example
Configure Spring Stomp
To configure Spring for STOMP messaging, you need to create a Java class named WebSocketConfig. This class is annotated with @Configuration to indicate that it's a Spring configuration class and @EnableWebSocketMessageBroker to enable WebSocket message handling.
The configureMessageBroker() method is used to configure the message broker, and it starts by enabling a simple memory-based message broker using the enableSimpleBroker() method. This allows the message broker to carry greeting messages back to the client on destinations prefixed with /topic.
Broaden your view: Websocket Spring Mvc
The /app prefix is designated for messages that are bound for methods annotated with @MessageMapping. This prefix will be used to define all the message mappings, such as /app/hello, which is the endpoint that the GreetingController.greeting() method is mapped to handle.
You also need to register the /gs-guide-websocket endpoint for WebSocket connections using the registerStompEndpoints() method.
Create A Browser
In this section, we'll focus on setting up the JavaScript client that will interact with our server-side WebSocket endpoint.
The JavaScript client imports the StompJS library to communicate with the server over STOMP over WebSocket. It also imports the app.js file, which contains the client application's logic.
The main pieces of the JavaScript file to understand are the stompClient.onConnect and sendName functions. The stompClient is initialized with the brokerURL referring to the path /gs-guide-websocket, where the WebSocket server waits for connections.
Upon a successful connection, the client subscribes to the /topic/greetings destination, where the server will publish greeting messages. When a greeting is received on that destination, it appends a paragraph element to the DOM to display the greeting message.
The sendName() function retrieves the name entered by the user and uses the STOMP client to send it to the /app/hello destination, where GreetingController.greeting() will receive it.
Test The Service
To test the service, point your browser at http://localhost:8080 and click the Connect button.
You'll be asked for your name, so enter it and click Send. Your name is sent to the server as a JSON message over STOMP.
After a one-second simulated delay, the server sends a message back with a “Hello” greeting that is displayed on the page.
You can send another name or click the Disconnect button to close the connection.
Readers also liked: Websocket Send
Overview
WebSocket is a powerful protocol for enabling real-time communication between clients and servers over the web.
WebSocket operates by first establishing an initial handshake between the client and server using HTTP, and then upgrading to the WebSocket protocol.
This process eliminates the need for repeated HTTP requests, reducing network overhead and making it particularly well-suited for applications that require instant updates.
WebSocket messages are typically lightweight and can be sent in either text or binary format, making it a flexible and efficient choice for real-time communication.
Expand your knowledge: Websocket vs Http
Many popular web frameworks and libraries provide support for WebSocket, making it relatively easy for developers to integrate into their projects.
WebSocket is supported by most modern web browsers, allowing developers to build real-time web applications that take advantage of its benefits.
By maintaining an open connection, WebSocket reduces latency and improves efficiency, making it a great choice for applications that require interactive features.
Backend Platforms
Node.js is a popular choice for building WebSocket servers due to its non-blocking I/O model, which makes it well-suited for handling multiple concurrent connections.
This architecture allows Node.js to efficiently handle high levels of concurrency without blocking the execution of other tasks. Node.js is built on an event-driven model, which simplifies the development of WebSocket servers.
Asynchronous programming is also a key feature of Node.js, making it easier to write code that handles WebSocket events without blocking the event loop. With its support for callbacks, promises, and async/await, developers can write efficient WebSocket server code.
A different take: Next Js Socket Io
Node.js is known for its performance and scalability when handling asynchronous I/O operations. With proper optimization and tuning, Node.js can deliver high performance for WebSocket-based applications.
You have two main options for building a WebSocket server with Node.js: ws and socket.io. Both libraries are good choices, but ws is more popular as it's written specifically for Node.js.
Here's a brief comparison of the two libraries:
- ws: more popular, written specifically for Node.js
- socket.io: has ports to all modern languages
Implementing a WebSocket server using ws takes just a few lines of code, making it a great choice for developers who want a straightforward implementation.
Frontend
On the frontend, you can use RxJS with WebSockets to handle real-time data streams in web applications. This powerful combination enables developers to handle WebSocket events in a reactive and composable manner.
You can use the WebSocket API to establish a connection to a server, and then use RxJS to handle the events that come from that connection. For example, you can use the `stompClient.onConnect` function to handle a successful connection to the server, and then subscribe to a destination to receive messages.
For more insights, see: When to Use Websockets

Using a library like StompJS can simplify the process of communicating with a WebSocket server. This library provides a JavaScript client that can be used to communicate with a server over WebSocket, and it's particularly useful when you need to handle reconnecting to the server if the connection is closed.
Suggestion: Python Websocket Library
Create A Browser
To create a browser client for your frontend application, you'll need to import the StompJS javascript library to communicate with your server through STOMP over websocket.
This HTML file imports the StompJS library, which is used to send and receive messages from the server side. The StompJS library is initialized with a broker URL, which in this case is /gs-guide-websocket, where the websockets server waits for connections.
Upon a successful connection, the client subscribes to the /topic/greetings destination, where the server will publish greeting messages. The client will append a paragraph element to the DOM to display the greeting message when one is received.
The sendName() function retrieves the name entered by the user and uses the STOMP client to send it to the /app/hello destination. The GreetingController.greeting() method will receive this message on the server side.
The client's logic is contained in the app.js file, which imports the StompJS library and contains the main pieces of the client application. The stompClient.onConnect function is used to handle a successful connection, and the sendName function is used to send the user's name to the server.
React Popular Libraries
React-use-websocket is a specialized Hook library that simplifies WebSocket integration in React applications.
When working with WebSockets in React, using a library can improve code readability and boost productivity by providing pre-developed features.
We used the ws library in Node.js to create WebSocket servers or client instances because Node.js doesn't offer an inbuilt API for this purpose.
Using libraries like React-use-websocket can help establish WebSocket connections, manage their lifecycle, and handle real-time data exchange within a React component.
For example, the React useWebSocket library comes with a simple way to connect to a WebSocket server, write less implementation code, and handle real-time data exchange.
For another approach, see: Websocket and Node Js
What Is WsCat?
WsCat is a command-line tool for WebSocket communication testing and debugging.
It allows you to interact with WebSocket servers directly from the terminal.
This makes it useful for debugging WebSocket connections and testing server responses.
WsCat is also great for experimenting with WebSocket APIs.
You can connect to your WebSocket server using this tool.
If you're working with a local server and using self-signed certificates, you may need to disable SSL certificate verification.
Competitors
When working with WebSockets, you may wonder about the alternatives. Polling is a simple approach, but it can be inefficient, especially if updates are infrequent or frequent checks are needed.
Polling involves the client repeatedly sending requests to the server at regular intervals to check for updates. This can be a problem if updates are rare, as it wastes resources.
Long polling is another approach that keeps a connection open for an extended period, simulating real-time communication. However, it can introduce latency compared to WebSocket.
Long polling also holds onto the request until new data is available, which can be less efficient than other methods.
Server-Sent Events (SSE) is a unidirectional communication protocol that allows the server to push updates to the client over a single HTTP connection. This is well-suited for scenarios where the server needs to push updates to the client.
Here are the competitors to WebSockets:
- Polling
- Long polling
- Server-Sent Events (SSE)
These alternatives have their own strengths and weaknesses, but WebSockets offer a more efficient and scalable solution.
Why to Use
WebSockets are designed to supersede existing bidirectional communication methods, making them a reliable and efficient choice for full-duplex real-time communications.
WebSockets allow messages to be sent from the client to the server, eliminating connection restrictions that come with other methods.
Socket.IO is a great choice for React apps, especially when you want features like chat or live updates without managing the messy parts yourself.
Native WebSocket is the raw, browser-standard option, but it comes with more manual work, like handling reconnections and parsing messages.
Socket.IO uses WebSocket underneath when possible, adding its own protocol on top, which gives us extras like automatic reconnection, fallback support, and easy event handling.
Consider reading: Socket Io Golang
Node.js and React Basics
Node.js is a JavaScript runtime environment that allows developers to create server-side applications. It's the foundation for a WebSocket server.
To create a Node.js server, you can spin one off and connect it to a client, as seen in the example of using WebSockets with Node.js and React. This setup enables real-time communication between the server and client.
A client built with React can be connected to a Node.js server using WebSockets, making it possible to establish a persistent connection between the two.
A different take: React Python Websocket
Node.js
Node.js is a popular runtime environment for executing JavaScript on the server side. To create a WebSocket client in Node.js, you can use the 'ws' library. This library is a popular choice for Node.js WebSocket implementations.
You can use the 'ws' library to create a simple WebSocket client in Node.js. This library provides a simple API for establishing WebSocket connections and managing their lifecycle.
Node.js doesn't offer an inbuilt API to create WebSocket servers or client instances, so using a WebSocket library like 'ws' is a good option. This library is widely used and has a large community of developers who contribute to it and provide support.
Take a look at this: Nextjs Tutorial Simple

To create a WebSocket client in Node.js, you need to install the 'ws' library using npm. Once installed, you can use the library to establish a WebSocket connection to a server. The 'ws' library provides a simple API for sending and receiving messages over the WebSocket connection.
Here are some key benefits of using the 'ws' library for Node.js WebSocket implementations:
- Easy to use and set up
- Provides a simple API for establishing WebSocket connections
- Supports bidirectional communication
- Has a large community of developers who contribute to it and provide support
Overall, the 'ws' library is a popular and reliable choice for Node.js WebSocket implementations. It provides a simple and easy-to-use API for establishing WebSocket connections and managing their lifecycle.
Python
Python is a popular language used in web development, and it's great for building the backend of your application.
You can use libraries like the WebSocket library to create a WebSocket client in Python, which allows for bidirectional communication between the client and server.
To create a WebSocket client in Python, you can use the WebSocket library as follows.
A WebSocket client in Python can be created using the WebSocket library, which is a simple and efficient way to establish real-time communication between your application and the server.
The WebSocket library for Python provides a straightforward way to create a WebSocket client, making it easy to get started with real-time web development.
You might like: Websocket Use Cases
Handshake Between Servers

A handshake between servers is a crucial step in establishing a WebSocket connection.
This handshake is initiated by the client, which sends a GET request to the server with a specific URL, typically in the form of ws://example.com/path.
The server responds with a 101 Switching Protocols status code, indicating that the connection will be upgraded to a WebSocket connection.
The client then sends a connection request, which includes a list of supported sub-protocols.
The server responds with a list of supported sub-protocols and the connection is established.
Server-Side Handshake with Node.js
To create a handshake at the server level with Node.js, you can use a single port to spin off the HTTP server and attach the WebSocket server. This can be done using the ws library to attach a WebSocket server instance to an HTTP server instance.
The WebSocket server will accept incoming WebSocket connection requests by upgrading the protocol from HTTP to WebSocket. I maintain all the connected clients as an object in my code with a unique key generated via the uuid package on receiving their request from the browser.

When you open the app with a new browser tab, you’ll see a generated UUID on your terminal. This UUID is used as a unique key to identify each client.
Using the ws library makes it easy to attach the WebSocket server to the HTTP server instance, and it will automatically accept WebSocket connections. This allows for real-time communication between the client and server.
The client and server are connected via the WebSocket handshake event, enabling the WebSocket connection to transmit messages as it receives them. This is a key feature of the WebSocket protocol.
For more insights, see: Sec Websocket Key
Swift
In Swift, you can establish a WebSocket connection using the URLSessionWebSocketTask API.
The URLSessionWebSocketTask API allows you to establish a WebSocket connection and listen for messages. You can use the sendMessage function to send a message to the WebSocket server.
With Swift, you can send a message to a WebSocket server and expect a response. This is useful for building servers that accept messages and push greetings into a queue.
If this caught your attention, see: Swift Websocket

The sendMessage function sends a message to the WebSocket server, and the connection is disconnected after a 5-second delay. This can be useful for testing and debugging purposes.
You will build a server that accepts a message carrying a user's name and pushes a greeting into a queue to which the client is subscribed. This is a great way to learn about WebSocket connections in Swift.
Server to Browser传输
Server to browser transmission is a crucial aspect of WebSockets. In JavaScript, you receive WebSocket messages by listening to message events.
To receive a message from the server and deserialize it from JSON, you can use the following code: `ws.onmessage = (event) => { const message = JSON.parse(event.data); // dispatch events depending on their type }`.
You'll need to handle three types of messages from the server to the browser: "play", "update", and "winner". Each type will trigger a specific action in the user interface.

Here's a summary of the message types and their corresponding actions:
To send an event from the server, you can use the `json.dumps()` method to serialize the event. For example: `ws.send(json.dumps({"type": "play", "move": 3}))`. Don't forget to restart the WebSocket server and reload the page in the browser when you make changes.
Add Game Logic
In the handler() coroutine, you're going to initialize a game. This is where the magic happens, and your game starts to take shape.
You'll iterate over incoming messages, taking specific steps to parse and process each event. The only type of event you need to worry about is "play", which is sent by the user interface.
To play the move in the board, you'll use the play() method, alternating between the two players. This is how the game will flow back and forth between players.
If the play() method raises a ValueError because the move is illegal, you'll send an event of type "error". This lets the user interface know that the move wasn't valid.

If the move is valid, you'll send an event of type "play" to tell the user interface where the checker lands. This keeps the game state up to date on both ends.
If the move wins the game, you'll send an event of type "win". This is the final step in the game, and it marks the end of the match.
Here are the steps to process incoming messages:
- Parse an event of type "play"
- Play the move in the board with the play() method
- If play() raises ValueError, send an event of type "error"
- Else, send an event of type "play" to tell the user interface where the checker lands
- If the move won the game, send an event of type "win"
Summary
You can build and run a WebSocket server in Python with the serve() function.
To receive messages in a connection handler, you use the recv() function.
Sending messages in a connection handler is done with the send() function.
You can iterate over incoming messages with async for message in websocket:.
To open a WebSocket connection in JavaScript, you use the WebSocket API.
Sending messages in a browser is done with WebSocket.send().
Receiving messages in a browser is done by listening to message events.
The tutorial has designed a set of events to be exchanged between the browser and the server.
The Protocol

The WebSocket protocol is a game-changer for real-time communication between clients and servers.
It offers persistent, real-time, full-duplex communication over a single TCP socket connection.
The protocol has only two agendas: to open up a handshake and to help the data transfer.
Once a handshake is accepted, data can be sent back and forth with minimal overhead.
WebSocket communication takes place over a single TCP socket using either the WS (port 80) or WSS (port 443) protocol.
Most browsers, except Opera Mini, have excellent support for WebSockets.
This means you can use WebSockets in your projects with confidence.
The protocol is designed to be simple and efficient, making it a great choice for real-time applications.
Curious to learn more? Check out: Websocket vs Socket
Http Connection Accepted
The HTTP connection is accepted when the client includes the Sec-WebSocket-Key in the request headers. This value is then encoded and hashed by the server, and a predefined GUID is added to it.
The server echoes the generated value in the Sec-WebSocket-Accept header field in the server-sent handshake. This indicates whether the server is willing to accept the connection or not.
A status code of 101, or "switching protocols", is sent by the server to confirm the successful handshake. This is the expected response if the WebSocket upgrade is successful.
The server's response must include an Upgrade header field with the value "websocket" to confirm the WebSocket connection.
Check this out: Sec Websocket Protocol
Initializing

Initializing a WebSocket client is straightforward. You create a new WebSocket object with the desired endpoint as a parameter.
The endpoint is the address of the WebSocket server you want to connect to. For example, in JavaScript, you would use the WebSocket constructor like this: `var ws = new WebSocket('ws://example.com');`.
To initialize a WebSocket client, you need to create a new WebSocket object with the desired endpoint as a parameter.
Take a look at this: Asp.net Websocket Example
Types of
All major languages have a WebSocket implementation, either as part of the language itself or provided by a standard or popular package.
The code examples below give the typical implementation of a WebSocket client in different programming languages and, where appropriate, provide dependencies.
You can find WebSocket implementations in various languages, including JavaScript, which is often used for client-side scripting in web browsers.
Major languages like JavaScript, Python, and Java have WebSocket implementations that make it easy to establish real-time communication between clients and servers.

Many popular packages, such as Node.js for JavaScript, provide WebSocket implementations that simplify the development process.
For example, in JavaScript, you can use the WebSocket API to establish a connection to a server.
Similarly, in Python, you can use the websockets library to create a WebSocket client.
In Java, you can use the javax.websocket API to establish a WebSocket connection.
These implementations make it easy to get started with WebSocket development, regardless of your programming language of choice.
Building Real-Time Apps
Building real-time apps is a breeze with WebSocket clients. You can create powerful and responsive applications that cater to modern user demands. Real-time applications can range from chat applications and online gaming to live data streaming and collaborative platforms.
To build real-time applications, you'll need to choose the right programming language, implement a WebSocket server, and design your application's architecture. This includes defining message formats, establishing connection management strategies, and designing the user interface to handle real-time updates.

Here are the essential steps to follow when building real-time applications using WebSocket clients:
- Choose a programming language that supports WebSocket clients, such as JavaScript, Python, or React.
- Implement a WebSocket server to manage incoming connections and handle data exchange.
- Design your application's architecture, including message formats, connection management strategies, and user interface design.
Remember, handling WebSocket events is crucial for managing the lifecycle of WebSocket connections. This includes defining event handlers for onopen, onmessage, onerror, and onclose events to exchange messages and handle errors.
HTTP Polling, Streaming, and Server-Sent Events
Historically, real-time web apps relied on abusing the HTTP protocol to establish bidirectional data transfer.
HTTP polling was one of the methods used, but it's inefficient because it requires the client to repeatedly send requests to the server to check for updates.
HTTP streaming is another approach, but it can lead to server overload and increased latency.
Comet, a technique that uses long-lived HTTP requests, also has its drawbacks, including server resource consumption and difficulty in debugging.
Server-sent events (SSE) is a method that allows servers to push updates to clients, but it's limited in its ability to handle bidirectional communication.
These methods all have their limitations, making WebSocket a more efficient choice for real-time web apps.
Server to Browser传输

To receive messages from the server, you need to listen to message events in JavaScript. This is done by calling the `onmessage` event on the WebSocket object.
You'll need to deserialize the JSON message received from the server. This can be done using the `JSON.parse()` method.
Three types of messages from the server to the browser are required: "play", "move", and "winner". These messages will be dispatched to the corresponding event handlers, which will take appropriate action.
Here's an example of how to receive a message from the server and deserialize it from JSON:
```javascript
ws.onmessage = function(event) {
var data = JSON.parse(event.data);
if (data.type === 'play') {
// playMove function will be called
} else if (data.type === 'move') {
// moveMove function will be called
} else if (data.type === 'winner') {
// alert will be shown
}
};
```
Note that you must restart the WebSocket server and reload the page in the browser when you make changes.
Featured Images: pexels.com


