18 – Real-World Python Projects – YouTube Video Downloader

๐ŸŽฏ Project Objective

Build a real-time chat application using Python sockets that allows multiple users to connect to a common server and exchange messages instantly.


๐Ÿง  Skills Youโ€™ll Learn

  • Socket programming (TCP communication)
  • Client-server architecture
  • Multithreading for handling multiple users
  • GUI design using Tkinter (optional)
  • Network message broadcasting

๐Ÿ—๏ธ Project Overview

Youโ€™ll create:

  1. Server script (server.py) โ€” handles connections and broadcasts messages to all clients.
  2. Client script (client.py) โ€” allows users to send and receive messages in real-time.

This setup works locally (LAN) or across a Wi-Fi network if both devices are connected to the same router.


โš™๏ธ Technology Stack

LibraryPurpose
socketEnables network communication between server and clients
threadingAllows concurrent handling of multiple clients
tkinter (optional)GUI for chat interface
sys, osCommand-line control and system utilities

๐Ÿงพ File 1 โ€“ Server (server.py)

import socket
import threading

# Server Configuration
HOST = '127.0.0.1'  # Localhost (use your IP for LAN)
PORT = 55555

# Create Socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen()

clients = []
nicknames = []

def broadcast(message):
    """Send message to all connected clients"""
    for client in clients:
        client.send(message)

def handle(client):
    """Handle messages from a single client"""
    while True:
        try:
            message = client.recv(1024)
            broadcast(message)
        except:
            # Remove client if connection is lost
            index = clients.index(client)
            clients.remove(client)
            client.close()
            nickname = nicknames[index]
            broadcast(f'{nickname} left the chat!'.encode('utf-8'))
            nicknames.remove(nickname)
            break

def receive():
    """Accept new client connections"""
    print("Server is running and listening...")
    while True:
        client, address = server.accept()
        print(f"Connected with {str(address)}")

        client.send('NICK'.encode('utf-8'))
        nickname = client.recv(1024).decode('utf-8')
        nicknames.append(nickname)
        clients.append(client)

        print(f"Nickname of the client is {nickname}")
        broadcast(f"{nickname} joined the chat!".encode('utf-8'))
        client.send("Connected to the server!".encode('utf-8'))

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

receive()

๐Ÿ’ป File 2 โ€“ Client (client.py)

import socket
import threading

nickname = input("Choose your nickname: ")

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('127.0.0.1', 55555))

def receive():
    while True:
        try:
            message = client.recv(1024).decode('utf-8')
            if message == 'NICK':
                client.send(nickname.encode('utf-8'))
            else:
                print(message)
        except:
            print("An error occurred!")
            client.close()
            break

def write():
    while True:
        message = f'{nickname}: {input("")}'
        client.send(message.encode('utf-8'))

# Threads for reading and writing
receive_thread = threading.Thread(target=receive)
receive_thread.start()

write_thread = threading.Thread(target=write)
write_thread.start()

๐Ÿงฉ How It Works

๐Ÿ”น Step 1 โ€” Start the Server

Run server.py in one terminal:

Server is running and listening...

๐Ÿ”น Step 2 โ€” Start Multiple Clients

Run client.py in separate terminals (or computers on the same network).

Example interaction:

User1: Hello everyone!
User2: Hi, User1 ๐Ÿ‘‹
User3: How are you all?

๐Ÿงฑ Architecture Diagram

        โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
        โ”‚    Server (Host)   โ”‚
        โ”‚  โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€  โ”‚
        โ”‚  socket + threads  โ”‚
        โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                 โ”‚
 โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
 โ”‚               โ”‚                โ”‚
โ–ผ               โ–ผ                โ–ผ
Client 1      Client 2         Client 3
(User1)       (User2)          (User3)

๐ŸŒ LAN Setup (Optional)

If you want to chat across computers on the same Wi-Fi:

  1. Replace HOST = '127.0.0.1' with your local IP address (found via ipconfig or ifconfig).
  2. Run the server on your main PC.
  3. Connect from other computers using that IP.

๐Ÿ’ก Bonus: GUI Chat Client (Optional)

You can add this using tkinter for a polished interface:

from tkinter import *
import threading, socket

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('127.0.0.1', 55555))

def receive():
    while True:
        try:
            message = client.recv(1024).decode('utf-8')
            chat_box.insert(END, message + '\n')
        except:
            print("Disconnected")
            client.close()
            break

def send_message():
    message = f"{nickname.get()}: {msg_entry.get()}"
    client.send(message.encode('utf-8'))
    msg_entry.delete(0, END)

root = Tk()
root.title("Python Chat App")

chat_box = Text(root, bg="white", width=50, height=15)
chat_box.pack()

msg_entry = Entry(root, width=40)
msg_entry.pack(side=LEFT, padx=5)

send_btn = Button(root, text="Send", command=send_message)
send_btn.pack(side=LEFT)

nickname = StringVar()
nickname.set(input("Enter your nickname: "))

threading.Thread(target=receive).start()
root.mainloop()

๐Ÿง  Learning Outcomes

After completing this project, youโ€™ll:

  • Understand TCP/IP communication
  • Learn to use threads for concurrency
  • Manage multiple clients in real-time
  • Build real network-based applications

๐Ÿš€ Project Enhancements (Next Steps)

FeatureDescription
๐Ÿ—‚๏ธ Private ChatAllow direct messaging between two users
๐Ÿงพ Message HistorySave all messages in a text or SQLite file
๐Ÿ”’ EncryptionSecure chat messages with cryptography
๐ŸŒ Web VersionConvert to Flask + SocketIO for browser chat
๐ŸŽจ GUI StylingAdd emojis, timestamps, themes


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *