
Real-time communication is a key feature of modern web applications, and Python WebSockets make it possible.
With Python WebSockets, you can establish persistent, low-latency connections between clients and servers, enabling real-time updates and interactions.
This is particularly useful for applications like live chat, gaming, and collaborative editing, where users expect immediate feedback and updates.
In a live chat application, for example, Python WebSockets can be used to push new messages to connected clients as they are received, creating a seamless and engaging user experience.
Expand your knowledge: How Do Websockets Improve Real-time Communication in Web Applications
What Are Web Sockets?
WebSockets are a communication protocol designed for full-duplex communication channels over a single TCP connection. This means both the client and server can send and receive data at the same time.
WebSockets reduce latency and overhead associated with traditional HTTP requests, making them ideal for real-time applications. This is especially useful for applications that require instant updates.
WebSockets provide a persistent connection, eliminating the need to repeatedly open and close connections. This results in a more efficient and reliable communication channel.
WebSockets are built on top of asyncio, Python's standard asynchronous I/O framework. This provides an elegant coroutine-based API for building WebSocket servers and clients.
WebSockets are also available with an implementation on top of threading and a Sans-I/O implementation.
Worth a look: Python Convert Float T O Int
Why Use Web Sockets?
WebSockets offer a number of advantages that make them an attractive choice for Python developers. Here are just a few reasons why you should consider using WebSockets in your next project.
WebSockets are heavily tested for compliance with RFC 6455, ensuring correctness and reliability in your application. Continuous integration fails under 100% branch coverage, which means you can trust that WebSockets will work as expected.
One of the biggest benefits of WebSockets is their simplicity. With WebSockets, you only need to understand two basic concepts: msg = await ws.recv() and await ws.send(msg). This makes it easy to focus on your application without getting bogged down in complex connection management.
WebSockets are built for production, which means they're robust and reliable. For example, they were the only library to handle backpressure correctly before the issue became widely known in the Python community.
Here are some of the key advantages of WebSockets:
- Low Latency: Because the connection stays open, messages can go back and forth without the delay of setting up a new request each time.
- Reduced Overhead: With WebSockets, there's less data to send and process compared to traditional HTTP requests.
- Two-Way Communication: Both sides of the connection can talk to each other at any time, making it ideal for real-time applications.
- Scalability: A single WebSocket server can handle many active connections at once, making it a good fit for large-scale applications.
WebSockets also offer improved performance, with memory usage optimized and configurable. A C extension accelerates expensive operations, making it a high-performance choice for Python developers.
Setting Up
To get started with Python websockets, you'll need to set up your environment properly. Installing the necessary tools and libraries is a straightforward process.
First, make sure you create a virtual environment to keep your project organized and dependencies isolated. This is a good practice to avoid conflicts with other projects.
Next, activate your virtual environment and install websockets. This will give you access to the websockets library and its features.
For your interest: Can Audio Be Sent through Websockets
Setting Up Environment
Getting your Python environment set up for real-time apps with WebSockets is pretty simple.
First, you need to create a virtual environment. This is a good practice to keep your project's dependencies separate from the system's Python installation.
Make sure your virtual environment is activated before proceeding. This will allow you to install packages without affecting the system's Python environment.
To install the necessary tools and libraries, you'll need to run some commands. Don't worry, I'll guide you through it.
You'll need to install the websockets library, which is a popular and easy-to-use library for building WebSocket servers and clients in Python.
To install it, run the following command in your activated virtual environment:
This command will download and install the websockets library and its dependencies.
Now that you have the websockets library installed, you can start building your real-time app.
A unique perspective: Building Python Web Apis with Fastapi
Create A
To create a WebSocket in your FastAPI application, use the WebSocket object directly from FastAPI or import it from starlette.websockets.
You can import the WebSocket object from either FastAPI or Starlette, as they are the same thing.
Curious to learn more? Check out: Fastapi Websockets
Server Implementation
To implement the server, we'll use the websockets library to create a WebSocket server. This server will handle incoming connections from clients, receive messages, and broadcast those messages to all connected clients.
The server will keep track of everyone currently connected in a set called connected_clients. The handle_client function adds new clients to this set, listens for messages they send, and then passes those messages along to everyone else.
We'll create a file named server.py and add the necessary code to get the server up and running.
For another approach, see: Create Telegram Bot with Python
Server and Client Implementation
To build a WebSocket server and client, you'll need to use Python. We'll be using a basic example that sets up real-time messaging between clients connected to the same server.
A simple chat app is a great way to demonstrate how WebSocket works. This example shows how users can send messages back and forth as they happen.
The server implementation involves setting up a WebSocket server using Python. This allows multiple clients to connect and send messages in real-time.
In this example, we're using a small chat app to illustrate the concept of real-time messaging. Users can send messages and receive responses instantly.
To get started with the server implementation, you'll need to write the server code in Python. This code will handle incoming connections and messages from clients.
The client implementation is where users interact with the chat app. They can send messages and receive responses from the server in real-time.
In this example, we're using a simple WebSocket client to connect to the server. This allows users to send messages and receive responses as they happen.
Server

The server is the backbone of our WebSocket setup, and it's where all the magic happens. To create a WebSocket server, we'll use the websockets library. This library will handle incoming connections from clients, receive messages, and broadcast those messages to all connected clients.
The server is created by bringing in the asyncio and websockets modules, which let us handle asynchronous tasks and WebSocket connections. We'll use a set called connected_clients to keep track of everyone currently connected.
Each time a new client joins, the handle_client function adds them to that set, listens for anything they send, and then passes their messages along to everyone else. This is a crucial part of our server implementation.
The main function sets up the server on localhost at port 12345 and waits for people to connect. We'll kick off the server by calling asyncio.run(main()).
Readers also liked: When to Use Websockets
Client Implementation
To create a WebSocket client in Python, you'll need a file named client.py. This file will contain the code that connects to the WebSocket server, sends messages, and receives messages from other clients.
Recommended read: Python save Html to File
The chat function in the client.py file connects to the WebSocket server running at ws://localhost:12345. The server's address is specified in this line of code.
Once connected, the chat function enters a loop where it asks the user for a message. This is a crucial step in the client-server communication process.
The user's message is sent to the server, and the client then prints whatever comes back. This is a simple yet effective way to establish a conversation between the client and server.
To get things going, you'll need to call asyncio.run(chat()). This line of code runs the chat function and sets the client in motion.
A unique perspective: Python Email Message
Real-time Communication
Real-time communication is where WebSockets truly shine. WebSockets allow for instant communication between clients and servers, making it perfect for applications that require real-time updates.
With WebSockets, you can send and receive data as soon as it's available, without having to refresh the page or wait for the server to respond. This is particularly useful in chat apps, where messages can be passed around instantly, and in games that involve multiple players, where everyone sees the action in real-time.
Some examples of real-time communication use cases include chat apps, collaborative document editing, and multiplayer games. WebSockets make it all possible by providing a robust and efficient way to send and receive data in real-time.
Here are some ways to send data using WebSockets:
- await websocket.send_text(data)
- await websocket.send_bytes(data)
- await websocket.send_json(data)
Note that JSON messages default to being sent over text data frames from version 0.10.0 onwards, but you can use websocket.send_json(data, mode="binary") to send JSON over binary data frames.
Use Cases
Some apps just don't work well if you have to keep refreshing the page or wait for the server to reply before anything happens.
Chat apps benefit a lot from WebSockets, making conversations feel more like real conversations. Messages can be passed around instantly.
Games that involve more than one player also benefit a lot from this - when someone moves or takes an action, everyone else sees it right away.
Apps where people are working together, like editing the same document or board at the same time, also use WebSockets to send and receive data in real-time.
Connected devices - like sensors, switches, or monitors - benefit from WebSockets too, allowing for instant data exchange without needing to make new requests every few seconds.
Real-time Communication
Real-time communication is all about keeping the conversation going without interruptions. WebSockets make this possible by allowing messages to be passed instantly between the client and server.
WebSockets are a great fit for chat apps, where messages can be passed around instantly, making conversations feel more like real conversations. They're also useful in apps where people are working together, like editing the same document or board at the same time.
To send data over WebSockets, you can use the `websocket.send_text()`, `websocket.send_bytes()`, or `websocket.send_json()` methods. For example, to send a JSON message, you can use `await websocket.send_json(data)`.
Here are some ways to send and receive data over WebSockets:
- Send text data: `await websocket.send_text(data)`
- Send binary data: `await websocket.send_bytes(data)`
- Send JSON data: `await websocket.send_json(data)`
- Receive data: `await websocket.receive()`
WebSockets are designed to handle real-time communication, and they're built for production. They're tested for compliance with RFC 6455 and have a robust architecture that can handle backpressure correctly.
Data Exchange
Data exchange is a crucial aspect of working with websockets in Python. You can send data to a client using the `websocket.send_text()`, `websocket.send_bytes()`, or `websocket.send_json()` methods.
These methods allow you to send text, binary, or JSON data to the client. Note that JSON messages default to being sent over text data frames from version 0.10.0 onwards.
To receive data from a client, you can use the `websocket.receive_text()`, `websocket.receive_bytes()`, or `websocket.receive_json()` methods. These methods return the received data as text, binary, or JSON, respectively.
Receiving JSON messages can be a bit tricky, as they default to being received over text data frames from version 0.10.0 onwards. However, you can use the `websocket.receive_json(data, mode="binary")` method to receive JSON over binary data frames.
Iterating over received data is also possible using the `websocket.iter_text()`, `websocket.iter_bytes()`, and `websocket.iter_json()` methods. These methods return an async iterator that yields the received data.
Here are the main methods for sending and receiving data:
- Send text: `websocket.send_text(data)`
- Send binary: `websocket.send_bytes(data)`
- Send JSON: `websocket.send_json(data)`
- Receive text: `websocket.receive_text()`
- Receive binary: `websocket.receive_bytes()`
- Receive JSON: `websocket.receive_json()`
Note that the `websocket.send()` and `websocket.receive()` methods can also be used to send and receive raw ASGI messages, ensuring that the websocket's state is correctly updated.
In addition to these methods, you can use the `await` keyword to wait for messages and send messages in your WebSocket route. This allows you to receive and send binary, text, and JSON data.
Related reading: Send Email from Python Gmail
Connection Management
Connection Management is crucial for a seamless WebSocket experience. You can catch and handle WebSocketDisconnect exceptions that occur when a client disconnects.
To handle disconnections, you can use a try-except block to catch the WebSocketDisconnect exception. This allows you to handle the disconnection in a way that suits your application.
For example, if you have multiple clients connected, closing one of the tabs will raise the WebSocketDisconnect exception. You can then send a message to all the other clients indicating that one of them has disconnected.
Here's a step-by-step guide to try out disconnection handling:
- Open the app with several browser tabs.
- Write messages from them.
- Then close one of the tabs.
This will raise the WebSocketDisconnect exception, and all the other clients will receive a message indicating that one of them has disconnected.
Security and Error Handling
WebSockets can be susceptible to certain types of attacks, such as Cross-Site WebSocket Hijacking, where an attacker uses a malicious website to establish a WebSocket connection to a different server that the user is authenticated with.
To mitigate these risks, you should add proper checks for authentication, authorization, and input validation.
Using secure WebSocket connections (wss://) helps keep data encrypted, protecting it from eavesdropping and tampering, which is essential for many modern use cases.
Here are some types of attacks to watch out for:
- Cross-Site WebSocket Hijacking
- DoS Attacks
Send Denial Response
Sending a denial response is a way to handle errors in a WebSocket connection. This can be done using the websocket.send_denial_response() method.
If you want to send a denial response, you'll need to use the websocket.send_denial_response() method. This method takes a response parameter, which you can await to send the response and close the connection.
The method requires the ASGI server to support the WebSocket Denial Response extension. If it's not supported, a RuntimeError will be raised.
You might like: Websocket Create Connection
Security Considerations
Security Considerations are crucial when working with WebSockets. Traditional HTTP security mechanisms are bypassed, making them susceptible to certain types of attacks.
Cross-Site WebSocket Hijacking is a real concern, where an attacker can use a malicious website to establish a WebSocket connection to a different server that the user is authenticated with.
To mitigate these risks, proper checks for authentication, authorization, and input validation are essential. This includes implementing secure WebSocket connections (wss://) to keep data encrypted and protect it from eavesdropping and tampering.
DoS Attacks can also occur, where an attacker opens multiple connections to exhaust server resources. This can be prevented by implementing proper checks and limiting the number of connections allowed.
Here are some common WebSocket security risks to be aware of:
- Cross-Site WebSocket Hijacking
- DoS Attacks
Getting Started
Traditional HTTP protocols can be reliable, but they're not ideal for real-time communication.
Their request-response model can be a challenge for applications that need low-latency, two-way communication between a client and a server.
This is where WebSockets come into play, making them a good fit for situations that demand real-time communication.
WebSockets are designed to provide a low-latency, two-way communication channel between a client and a server.
Installing the Library
Installing the library is a straightforward process. Make sure your virtual environment is activated.
To install the websockets library, run the following command in your terminal. This will download and install the library and its dependencies.
Create a virtual environment to isolate your project's dependencies. Activate it to start working on your project.
Run the installation command to install the websockets library. It's a popular and easy-to-use library for building WebSocket servers and clients in Python.
Make sure you're in the right directory before running the installation command. Otherwise, you might end up installing the library globally.
Basic Project Structure
When you're starting a new project, it's essential to keep things organized. This makes your code much easier to manage.
A basic project structure can help you achieve this. Here's a simple structure for our WebSocket project: venv/: The virtual environment directory containing the Python interpreter and installed libraries.server.py: The script for the WebSocket server.client.py: The script for the WebSocket client.README.md: A file providing an overview of the project and instructions for setup and usage.
Try It

To run your FastAPI application, simply open your browser at http://127.0.0.1:8000. You'll see a simple page where you can type messages in the input box and send them.
The application will respond back with a message, and you can send many messages, all using the same WebSocket connection.
You can test this by typing in the input box and sending the message. The application will respond back with a message, and you can continue to send and receive messages in real-time.
To get started, make sure your file is named main.py, as this is the default file name used in the example. If your file is named differently, you can adjust the command to run your application accordingly.
For your interest: Python Read Html File
Running the Application
To run the application, start by launching the WebSocket server on localhost at port 12345 by running a command in a terminal window.
This command starts the WebSocket server.
Open multiple terminal windows to start multiple clients, each of which connects to the server by running the following command.
This command starts a WebSocket client.
In each client terminal window, you can enter messages, which will be sent to the server and broadcast to all other connected clients in real-time.
Featured Images: pexels.com


