TCPChatRoom

← Back to Toolkit

Project Overview

This tool implements a real-time chat server and client using TCP sockets. It supports multiple clients, each handled in a separate thread, enabling concurrent message exchange.

Server Implementation

The server initializes with:

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

Upon accept(), each new client socket is passed to threading.Thread:

thread = threading.Thread(target=handle_client, args=(client_socket,))
thread.start()

The handle_client() function prefixes messages with usernames and invokes broadcast(message, sender) to distribute to all peers.

Message Broadcasting

The broadcast() helper ensures that messages from one client reach the others:

def broadcast(msg, sender):
    for client in clients:
        if client != sender:
            client.send(msg)

This design filters out the sender, preventing echo, and loops through the clients list for distribution.

Client Implementation

The client connects via:

client_socket.connect((HOST, PORT))

It spawns two threads for non-blocking I/O: one to receive data:

recv_thread = threading.Thread(target=receive_messages)
recv_thread.daemon = True
recv_thread.start()

And one to capture user input and send:

while True:
    msg = input()
    client_socket.send(msg.encode())

Key Takeaways

View Full Code on GitHub