Build a Python Chat Application: An End-to-End Example

In this tutorial, you will learn how to create a real-time chat application using Python. We will cover all the necessary steps, including setting up the server, creating the client, and designing a graphical user interface (GUI) for seamless communication.

Table of Contents

  1. Requirements and Installation
  2. Creating the Chat Server
  3. Creating the Chat Client
  4. Designing the GUI for the Chat Application
  5. Testing the Chat Application
  6. Conclusion

1. Requirements and Installation

To build our chat application, we will need the following:

  • Python 3.6 or higher
  • Tkinter for the GUI
  • Sockets for communication

First, ensure you have Python installed. If not, download it from the official website.

Next, install Tkinter:

pip install tk

2. Creating the Chat Server

The server will handle incoming connections and manage the messages between clients. Create a new file named server.py and add the following code:

import socket
import threading

class ChatServer:
    def __init__(self, host='127.0.0.1', port=5555):
        self.host = host
        self.port = port
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.bind((self.host, self.port))
        self.clients = []
        self.nicknames = []

    def broadcast(self, message):
        for client in self.clients:
            client.send(message)

    def handle(self, client):
        while True:
            try:
                message = client.recv(1024)
                self.broadcast(message)
            except:
                index = self.clients.index(client)
                self.clients.remove(client)
                client.close()
                nickname = self.nicknames[index]
                self.nicknames.remove(nickname)
                self.broadcast(f'{nickname} left the chat!'.encode('ascii'))
                break

    def receive(self):
        while True:
            client, address = self.server.accept()
            print(f'Connected with {str(address)}')

            client.send('NICK'.encode('ascii'))
            nickname = client.recv(1024).decode('ascii')
            self.nicknames.append(nickname)
            self.clients.append(client)

            print(f'Nickname of client is {nickname}!')
            self.broadcast(f'{nickname} joined the chat!'.encode('ascii'))
            client.send('Connected to the server!'.encode('ascii'))

            thread = threading.Thread(target=self.handle, args=(client,))
            thread.start()

if __name__ == '__main__':
    chat_server = ChatServer()
    chat_server.receive()

This code sets up a ChatServer class that listens for connections and manages client communication.

3. Creating the Chat Client

Now, we need to create a chat client to connect to the server. Create a new file named client.py and add the following code:

import socket
import threading

class ChatClient:
    def __init__(self, host='127.0.0.1', port=5555):
        self.host = host
        self.port = port
        self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.client.connect((self.host, self.port))

    def receive(self):
        while True:
            try:
                message = self.client.recv(1024).decode('ascii')
                print(message)
            except:
                print('Error occurred!')
                self.client.close()
                break

    def write(self, message):
        self.client.send(message.encode('ascii'))

if __name__ == '__main__':
    chat_client = ChatClient()
    receive_thread = threading.Thread(target=chat_client.receive)
    receive_thread.start()

    while True:
        message = input('')
        chat_client.write(message)

This code sets up a ChatClient class that connects to the specified server and sends messages to the server.

4. Designing the GUI for the Chat Application

Create a new file named app.py and add the following code to design the GUI using Tkinter:

import tkinter as tk
from client import ChatClient

class ChatApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.title('Python Chat App')
        self.geometry('500x400')

        self.chat_client = ChatClient()

        self.chat_listbox = tk.Listbox(self, bg='white', width=60, height=15, font=('Arial', 12))
        self.chat_listbox.pack(padx=5, pady=5)

        self.entry_var = tk.StringVar()
        self.entry = tk.Entry(self, textvariable=self.entry_var, font=('Arial', 12))
        self.entry.bind('<Return>', self.send_message)
        self.entry.pack(fill=tk.BOTH, padx=5, pady=5, ipadx=5, ipady=5)

        self.receive_thread = threading.Thread(target=self.receive_messages)
        self.receive_thread.start()

    def receive_messages(self):
        while True:
            message = self.chat_client.client.recv(1024).decode('ascii')
            self.chat_listbox.insert(tk.END, message)

    def send_message(self, event):
        message = self.entry_var.get()
        self.chat_listbox.insert(tk.END, f'You: {message}')
        self.chat_client.write(message)
        self.entry_var.set('')

if __name__ == '__main__':
    app = ChatApp()
    app.mainloop()

This code creates a simple GUI for the chat application, allowing users to send and receive messages.

5. Testing the Chat Application

To test the chat application, follow these steps:

  1. Run the server.py file to start the chat server.
  2. Run the app.py file to launch the chat application.
  3. Open another instance of app.py to simulate multiple users.
  4. Send messages between clients to test the functionality.

6. Conclusion

In this tutorial, we learned how to create a real-time chat application using Python. We set up a server and client, designed a simple GUI, and tested the app with multiple users. You can now expand on this project by adding more features, such as private messaging, group chats, and user authentication. Happy coding!

An AI coworker, not just a copilot

View VelocityAI