Building a Real-Time Chat Application using Python and WebSocket Technology


Real-time chat applications have become an integral part of our digital lives, revolutionizing the way we communicate and collaborate with others. Whether it's connecting with friends and family, collaborating with colleagues on a project, or engaging with customers on a website, real-time chat provides instant and seamless communication that enhances the user experience.

In this tutorial, we will dive into the world of real-time chat applications and explore how to build one using Python and WebSocket technology.

WebSocket is a communication protocol that enables full-duplex communication channels over a single TCP connection. It offers an efficient and lightweight solution for real-time applications by allowing continuous two-way communication between a server and clients. By utilizing WebSocket technology, we can create a chat application that delivers messages instantly and ensures a responsive and interactive user interface.

The Python programming language offers a wide range of libraries and frameworks for web development, making it an excellent choice for building real-time chat applications. One such library is `websockets`, which provides a simple and convenient way to implement WebSocket functionality in Python applications.

Through this tutorial, you can go through the process of building a real-time chat application using Python and WebSocket technology. We will cover the installation of the necessary library, setting up a WebSocket server, creating a WebSocket client, and demonstrating the communication between them.

By the end of this tutorial, you will have a solid understanding of how to leverage WebSocket technology to develop your own real-time chat application. Whether you are a beginner or an experienced Python developer, this tutorial will serve as a practical guide to get you started on the path of building real-time communication applications.

So, let's explore WebSocket technology and build a real-time chat application that will enhance your ability to connect, collaborate, and communicate in real-time with others.

Getting Started

Before diving into the code, we must install the WebSockets library. This can be done using the pip package manager. This module does not come pre-packaged with Python. So, we’ll be downloading and installing it using the pip package manager.

Open your terminal or command prompt and run the following command to install the library using pip −

pip install websockets

With the library installed successfully, we can proceed with building our real-time chat application!

Step 1: Setting up the WebSocket Server

To begin, let us set up the WebSocket server using the WebSockets library. Open your preferred Python integrated development environment (IDE) or text editor to begin writing the code. Import the necessary modules by adding the following lines of code at the beginning −

import asyncio
import websockets

The asyncio module provides the infrastructure for writing asynchronous code in Python, while the websockets module allows us to create WebSocket servers and clients.

Next, define an asynchronous function to handle incoming WebSocket connections −

async def handle_connection(websocket, path):
   # Code to handle incoming connections

In this code snippet, we define an asynchronous function named handle_message that takes two parameters: websocket and path. The websocket parameter represents the WebSocket connection, and the path parameter represents the URL path of the connection. Inside the handle_connection function, we can add logic to handle different WebSocket events, such as receiving messages, sending messages, and closing connections.

For example, we can implement a basic chat server that broadcasts messages to all connected clients −

async def handle_connection(websocket, path):
   # Add the websocket to a list of connected clients
   connected_clients.append(websocket)

   try:
      while True:
         # Receive a message from the client
         message = await websocket.recv()

         # Broadcast the message to all connected clients
         for client in connected_clients:
            await client.send(message)
   finally:
      # Remove the websocket from the list of connected clients
      connected_clients.remove(websocket)

Step 2: Setting up the WebSocket Client

Next, let's set up the WebSocket client to establish a connection with the server and send/receive messages. Create another Python file and import the necessary modules −

Define an asynchronous function to handle the client's WebSocket connection −

Inside the connect_to_server function, we can add logic to send and receive messages from the server. For instance, we can implement a basic chat client that allows the user to send messages −

async def connect_to_server():
   async with websockets.connect('ws://localhost:8000') as websocket:
      while True:
         # Get user input
         message = input("Enter message: ")

         # Send the message to the server
         await websocket.send(message)

         # Receive a message from the server
         response = await websocket.recv()

         # Print the received message
         print("Received:", response)

Step 3: Running the WebSocket Server and Client

WebSocket Server −

import asyncio
import websockets
connected_clients = []
async def handle_connection(websocket, path):
   # Add the websocket to a list of connected clients
   connected_clients.append(websocket)
   try:
      while True:
         # Receive a message from the client
         message = await websocket.recv()

         # Broadcast the message to all connected clients
         for client in connected_clients:
            await client.send(message)
   finally:
      # Remove the websocket from the list of connected clients
      connected_clients.remove(websocket)

# Start the WebSocket server
start_server = websockets.serve(handle_connection, 'localhost', 8000)
# Run the server indefinitely
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

The server is started by running the event loop. The run_until_complete method is called on the event loop, passing in the start_server object, which represents the WebSocket server. This ensures that the server is set up and ready to accept connections. To keep the server running indefinitely, the run_forever method is invoked on the event loop. This allows the server to continue listening for incoming connections and handling messages as they arrive. By running the code, you will have a WebSocket server up and running, ready to handle connections and facilitate real-time communication between clients.

WebSocket Client −

import asyncio
import websockets

async def connect_to_server():
   async with websockets.connect('ws://localhost:8000') as websocket:
      while True:
         # Get user input
         message = input("Enter message: ")

         # Send the message to the server
         await websocket.send(message)

         # Receive a message from the server
         response = await websocket.recv()

         # Print the received message
         print("Received:", response)

# Connect the WebSocket client
asyncio.get_event_loop().run_until_complete(connect_to_server())

Conclusion

In this tutorial, we explored how to build a real-time chat application using Python and WebSocket technology. We started by introducing the WebSocket protocol and its advantages for real-time communication. We used the WebSockets library to create a WebSocket server that can handle incoming connections and broadcast messages to all connected clients. Additionally, we built a WebSocket client that can connect to the server, send messages, and receive responses.

After setting up the WebSocket server and client, we implemented the basic functionality of a chat application. This involved establishing a connection between the client and server, handling incoming messages, and broadcasting messages to all connected clients.

By following the provided code examples and explanations, you should be able to create a real-time chat application using Python and WebSocket technology. You can further extend this application by adding features such as user authentication, private messaging, or message persistence.

You can explore the official documentation of the `websockets` library and WebSocket protocol to deepen your knowledge and explore advanced features. Additionally, don't hesitate to experiment and customize the code to suit your specific requirements and design preferences.

WebSocket technology provides a powerful and efficient means of implementing real-time communication in various applications, including chat applications, collaborative tools, real-time notifications, and multiplayer games. By following the steps outlined in this tutorial, you can create your own real-time chat application and explore the possibilities of WebSocket technology in your projects.

With the knowledge gained from this tutorial, you are now well-equipped to embark on your journey of building real-time chat applications using Python and WebSocket technology. Happy coding!

Updated on: 31-Aug-2023

524 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements