Building a Real-Time Chat Application with Python and WebSockets

 



Introduction

In this tutorial, we will build a real-time chat application using Python and WebSockets. WebSockets allow for two-way communication between a client and server, making them ideal for real-time applications like chat. We’ll use the websockets library for our WebSocket server and Tkinter for the client-side interface.

Prerequisites

  • Basic knowledge of Python
  • Python installed on your machine
  • Basic understanding of WebSockets
  • Familiarity with Tkinter for GUI development (optional)

Step 1: Setting Up the WebSocket Server

  1. Install Required Libraries

    First, install the websockets library using pip:

          pip install websockets


Create the WebSocket Server

Create a new Python file named server.py and add the following code:

import asyncio

import websockets


connected_clients = set()


async def handler(websocket, path):

    connected_clients.add(websocket)

    try:

        async for message in websocket:

            # Broadcast the message to all connected clients

            if connected_clients:

                await asyncio.wait([client.send(message) for client in connected_clients])

    finally:

        connected_clients.remove(websocket)


async def main():

    async with websockets.serve(handler, "localhost", 8765):

        await asyncio.Future()  # Run forever


if __name__ == "__main__":

    asyncio.run(main())


This code sets up a WebSocket server that listens on localhost and port 8765. It maintains a set of connected clients and broadcasts incoming messages to all clients.


Step 2: Creating the Client Interface

  1. Install Tkinter

    Tkinter is included with Python, so you typically don't need to install it separately. However, if you're using a virtual environment, ensure Tkinter is available.

  2. Create the Client Application

    Create a new Python file named client.py and add the following code:


import asyncio
import websockets
import tkinter as tk
from tkinter import scrolledtext

class ChatClient:
    def __init__(self, root):
        self.root = root
        self.root.title("Chat Client")
        
        self.text_area = scrolledtext.ScrolledText(self.root, state='disabled')
        self.text_area.pack(expand=True, fill='both')
        
        self.entry = tk.Entry(self.root)
        self.entry.bind("<Return>", self.send_message)
        self.entry.pack(fill='x')
        
        self.websocket = None
        asyncio.run(self.connect())

    async def connect(self):
        self.websocket = await websockets.connect("ws://localhost:8765")
        asyncio.create_task(self.receive_messages())

    async def receive_messages(self):
        async for message in self.websocket:
            self.text_area.config(state='normal')
            self.text_area.insert(tk.END, message + "\n")
            self.text_area.config(state='disabled')
            self.text_area.yview(tk.END)

    def send_message(self, event):
        message = self.entry.get()
        if message:
            asyncio.create_task(self.websocket.send(message))
            self.entry.delete(0, tk.END)

if __name__ == "__main__":
    root = tk.Tk()
    client = ChatClient(root)
    root.mainloop()


This code creates a simple GUI for the chat client using Tkinter. It connects to the WebSocket server and provides an interface to send and receive messages.

  1. This code creates a simple GUI for the chat client using Tkinter. It connects to the WebSocket server and provides an interface to send and receive messages.

Step 3: Running the Application

  1. Start the WebSocket Server

    Open a terminal and run:

python server.py

Run the Chat Client

Open another terminal and run:

python client.py

  1. You can run multiple instances of the client application to simulate different users.

Conclusion

In this tutorial, we’ve built a simple real-time chat application using Python and WebSockets. The server handles multiple clients and broadcasts messages to all connected clients. The client interface allows users to send and receive messages in real-time.

Feel free to extend this application by adding features like user authentication, message history, or more sophisticated UI elements. If you have any questions or need further assistance, let me know!


Building a Real-Time Chat Application with Python and WebSockets Building a Real-Time Chat Application with Python and WebSockets Reviewed by Medics on September 02, 2024 Rating: 5

No comments:

-->
Powered by Blogger.