SoFunction
Updated on 2025-03-10

Python develops a fully functional IM chat tool (with example code)

Instant messaging (IM) tools play an important role in our daily lives and work. From simple text chat to file transfers, audio and video calls, IM tools are rich in features and widely used. So, how to use Python to develop a simple IM chat tool?

In this blog, we will take you to implement a basic IM chat tool step by step and introduce how its core functions are implemented. The final tool will include:

  1. Client and server architecture
  2. Real-time message sending and receiving
  3. Multi-user chat support
  4. A simple graphical user interface (GUI)

1. Architectural design of IM tools

IM tools typically use the client-server architecture. The basic logic is as follows:

  1. Server: Responsible for managing user connections, forwarding messages to designated users, and ensuring the real-time and reliability of messages.
  2. Client: Responsible for user input and message sending, and at the same time receive messages from the server and display them to the user.

We will use Python's socket module to build network communication, use threading to implement multi-threading to handle connections between multiple users, and use tkinter to develop the client's graphical interface.

2. Server-side implementation

The server is responsible for listening to client connections, receiving and forwarding messages. We will create a simple server program:

Server code

import socket
import threading

# Save connected clientsclients = []

# Process client messagesdef handle_client(client_socket, client_address):
    print(f"[Connection successfully] {client_address}")
    while True:
        try:
            # Receive message            message = client_socket.recv(1024).decode('utf-8')
            if message:
                print(f"[Received a message] {client_address}: {message}")
                # Broadcast messages to other clients                broadcast(message, client_socket)
            else:
                remove_client(client_socket)
                break
        except:
            remove_client(client_socket)
            break

# Broadcast messagedef broadcast(message, sender_socket):
    for client in clients:
        if client != sender_socket:
            try:
                (('utf-8'))
            except:
                remove_client(client)

# Remove clientdef remove_client(client_socket):
    if client_socket in clients:
        (client_socket)
        print(f"[Disconnect] {client_socket.getpeername()}")

# Server main programdef server_program():
    server = (socket.AF_INET, socket.SOCK_STREAM)
    (('0.0.0.0', 12345))  # Listen to all IPs, port number 12345    (5)
    print("[Server Start] Listening to the connection...")

    while True:
        client_socket, client_address = ()
        (client_socket)
        (target=handle_client, args=(client_socket, client_address)).start()

if __name__ == "__main__":
    server_program()

Code parsing

  1. Listening for connection: The server listens for the client's connection request through () and ().
  2. Multithreading: Each connection will start a new thread to process the client's messages, ensuring that the server can handle multiple users at the same time.
  3. Message broadcast: Use broadcast() to forward messages to other connected clients.
  4. Client Management: Stores all currently connected clients through the clients list and removes them when the connection is disconnected.

3. Client implementation

The client needs to be able to send messages to the server and receive broadcast messages from the server at the same time. We also need a simple GUI to enhance the user experience.

Client Code

import socket
import threading
import tkinter as tk
from tkinter import scrolledtext

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

        # Create the main window         = ()
        ("IM Chat Tool")
        ("400x500")

        # Message display area        self.chat_area = (, wrap=, state='disabled')
        self.chat_area.pack(padx=10, pady=10, fill=, expand=True)

        # Message input box        self.message_entry = ()
        self.message_entry.pack(padx=10, pady=5, fill=)
        self.message_entry.bind("<Return>", self.send_message)

        # Send button        self.send_button = (, text="send", command=self.send_message)
        self.send_button.pack(padx=10, pady=5)

        # Start the receiving thread        (target=self.receive_messages, daemon=True).start()

        # Run the main window        ()

    def send_message(self, event=None):
        message = self.message_entry.get()
        if message:
            self.client_socket.send(('utf-8'))
            self.message_entry.delete(0, )

    def receive_messages(self):
        while True:
            try:
                message = self.client_socket.recv(1024).decode('utf-8')
                self.display_message(message)
            except:
                break

    def display_message(self, message):
        self.chat_area.config(state='normal')
        self.chat_area.insert(, message + '\n')
        self.chat_area.yview()
        self.chat_area.config(state='disabled')

if __name__ == "__main__":
    ChatClient()

Code parsing

  1. Connect with the server: The client uses () to connect to the address and port of the server.
  2. Message receiving thread: receive messages from the server in real time through independent thread receive_messages().
  3. GUI interface: Use Tkinter to create message display areas, input boxes, and send buttons to enhance the user experience.
  4. Message send: Send the message entered by the user to the server through send_message().

4. Running example

Start the server

Run server code:

python 

At this time, the server will start listening to the port and wait for the client to connect.

Start the client

Run client code:

python 

After starting multiple clients, the user can send messages, and the server will broadcast messages to all connected clients.

5. Functional extension

After the basic chat tool functions are implemented, you can further expand its functions:

  1. Username support: Set a username for each client and display the username when sending a message.
  2. Private chat function: Supports users to send private messages through commands or buttons.
  3. File transfer: implements file upload and download functions.
  4. Encrypted communication: Use SSL or other encryption methods to ensure the security of chat content.
  5. Beautify the interface: Beautify the chat interface by using ttk or third-party GUI libraries (such as PyQt, Kivy).

6. Summary

Through this blog, we built a simple IM chat tool using Python, covering the basic implementations of both server and client. While the tool only provides basic messaging and receiving functions, it lays a solid foundation for further expansion.

Instant messaging tools are excellent practice projects for web programming and GUI development. If you are interested in the project, you can try adding more advanced features such as user authentication, message history, and multimedia support.

This is the article about Python developing a full-featured IM chat tool (with example code) that ends with this article. For more related content on Python developing IM chat tool, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!