project

How to Make a Chat Application in Python

By May 10th, 2026No Comments6 min read
pip install colorama
import socket
from threading import Thread

# Server configuration
SERVER_HOST = "0.0.0.0"
SERVER_PORT = 5002
separator_token = "<SEP>"

# Store client sockets
client_sockets = set()

# Initialize the server socket
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((SERVER_HOST, SERVER_PORT))
s.listen(5)

print(f"[*] Listening as {SERVER_HOST}:{SERVER_PORT}")

def listen_for_client(cs):
    """Function to continuously listen for messages from a specific client."""
    while True:
        try:
            # Receive message from client
            msg = cs.recv(1024).decode()
        except Exception as e:
            # Handle client disconnection
            print(f"[!] Error: {e}")
            client_sockets.remove(cs)
            break
        else:
            # Replace separator token and broadcast the message
            msg = msg.replace(separator_token, ": ")
            for client_socket in client_sockets:
                client_socket.send(msg.encode())

while True:
    # Accept new client connections
    client_socket, client_address = s.accept()
    print(f"[+] {client_address} connected.")

    # Add the new client socket to the set
    client_sockets.add(client_socket)

    # Start a thread to listen to messages from this client
    t = Thread(target=listen_for_client, args=(client_socket,))
    t.daemon = True
    t.start()

# Close all sockets upon server shutdown
for cs in client_sockets:
    cs.close()
s.close()
import socket
import random
from threading import Thread
from datetime import datetime
from colorama import Fore, init

# Initialize colorama
init()

# Available colors for the chat clients
colors = [
    Fore.BLUE, Fore.CYAN, Fore.GREEN, Fore.LIGHTBLACK_EX, Fore.LIGHTBLUE_EX,
    Fore.LIGHTCYAN_EX, Fore.LIGHTGREEN_EX, Fore.LIGHTMAGENTA_EX,
    Fore.LIGHTRED_EX, Fore.LIGHTWHITE_EX, Fore.LIGHTYELLOW_EX, Fore.MAGENTA,
    Fore.RED, Fore.WHITE, Fore.YELLOW
]
client_color = random.choice(colors)

# Server details
SERVER_HOST = "127.0.0.1"
SERVER_PORT = 5002
separator_token = "<SEP>"

# Initialize the client socket
s = socket.socket()
print(f"[*] Connecting to {SERVER_HOST}:{SERVER_PORT}...")
s.connect((SERVER_HOST, SERVER_PORT))
print("[+] Connected.")

# Prompt for user's name
name = input("Enter your name: ")

def listen_for_messages():
    """Function to listen for incoming messages from the server."""
    while True:
        message = s.recv(1024).decode()
        print("\n" + message)

# Start a thread to listen for messages from the server
t = Thread(target=listen_for_messages)
t.daemon = True
t.start()

while True:
    # Get user input
    to_send = input()
    
    # If the user wants to exit
    if to_send.lower() == 'q':
        break

    # Add timestamp and format the message
    date_now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    to_send = f"{client_color}[{date_now}] {name}{separator_token}{to_send}{Fore.RESET}"

    # Send the message to the server
    s.send(to_send.encode())

# Close the connection
s.close()
python server.py
python client.py
sudo ufw allow 5002
Support Icon Support My Projects