Chat App (Sockets) Project (Code) in Python

← Back to Projects

Chat Application Using Sockets in Python (Client-Server Project)

This project demonstrates how to build a basic client-server chat application using Python sockets. It introduces the fundamentals of network programming, where multiple clients can connect to a central server and exchange messages in real time.

This application runs on localhost and is intended for learning purposes only. It does not include authentication, encryption, or internet deployment.

About the project:

This project is more advanced than a basic command-line chat simulation and focuses on real-time communication using sockets.

This project will consist of two separate Python scripts:

  • one for the server and one for the client.
  • You will need to run both scripts on your machine to see them communicate.


How the Socket Chat Application Works

The project follows a client-server architecture:

  • The server listens for incoming connections
  • Each client connects to the server using sockets
  • The server broadcasts received messages to all connected clients
  • Multithreading allows multiple users to chat simultaneously

To use this simple chat application, you need to run both scripts.

  1. Run the Server First:
    • Save the server code as server.py.
    • Open a terminal or command prompt.
    • Run the server: python server.py
    • The terminal will show "Server is listening on 127.0.0.1:65432".

    • Run One or More Clients:
    • Save the client code as client.py.
    • Open a new terminal or command prompt.
    • Run the client: python client.py
    • The terminal will show "Connected to server on 127.0.0.1:65432".
    • You can open multiple client terminals to simulate a chat between more than two users.

Now, any message you type in one client's terminal will be sent to the server and then broadcast to all other connected clients.


Prerequisites

  • Basic knowledge of Python
  • Understanding of functions and loops
  • Familiarity with command-line usage
  • Basic idea of client-server communication (helpful but not required)


Project Level: Intermediate

You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.

To test this chat application, you must run the server and client scripts in separate terminal windows on the same machine.

Steps: Follow these steps

Step 1: Copy below code using green 'copy' button.

Step 2: Paste the code on your chosen editor.

Step 3: Save the code with filename and .py extention.

Step 4: Run (Press F5 if using python IDLE)




# server.py

import socket
import threading
import sys

# Server configuration
HOST = '127.0.0.1' # Standard loopback interface address (localhost)
PORT = 65432       # Port to listen on (non-privileged ports are > 1023)

# List to keep track of connected clients
clients = []

def broadcast(message, sender_socket):
    """
    Sends a message to all connected clients except the sender.
    """
    for client in clients:
        if client != sender_socket:
            try:
                client.sendall(message)
            except:
                # If a client fails to receive, remove it
                client.close()
                remove_client(client)

def handle_client(client_socket, address):
    """
    Handles an individual client connection.
    Listens for messages and broadcasts them to other clients.
    """
    print(f"New connection from {address}")
    
    try:
        # Keep receiving messages from the client
        while True:
            message = client_socket.recv(1024)
            if message:
                print(f"Received from {address}: {message.decode('utf-8')}")
                broadcast(message, client_socket)
            else:
                # No message means the client disconnected
                print(f"Client {address} disconnected.")
                remove_client(client_socket)
                break
    except Exception as e:
        print(f"Error with client {address}: {e}")
        remove_client(client_socket)

def remove_client(client_socket):
    """
    Removes a client from the list of active clients.
    """
    if client_socket in clients:
        clients.remove(client_socket)
        
def main():
    """
    Main function to start the chat server.
    """
    server_socket = None
    try:
        # Create a socket and bind it to the host and port
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_socket.bind((HOST, PORT))
        server_socket.listen()
        
        print(f"Server is listening on {HOST}:{PORT}")
        
        while True:
            # Wait for a new client to connect
            client_socket, address = server_socket.accept()
            clients.append(client_socket)
            
            # Start a new thread to handle the client
            client_handler = threading.Thread(target=handle_client, args=(client_socket, address))
            client_handler.daemon = True # Allow threads to exit when main program exits
            client_handler.start()
            
    except KeyboardInterrupt:
        print("\nServer is shutting down.")
    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        if server_socket:
            server_socket.close()

# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
    main()





What You Will Learn From This Project

  • How sockets work in Python
  • How to create a TCP server and client
  • How multithreading enables multiple connections
  • How messages are sent and received over a network
  • Basic real-time communication concepts

Limitations and Security Notes

This project does not include encryption, authentication, or user validation. All messages are sent in plain text over local sockets.

For real-world chat applications, technologies such as SSL/TLS, authentication, and message encryption are required.


Ideas to Extend This Project

  • Add usernames for each client
  • Encrypt messages using SSL sockets
  • Store chat history in a file or database
  • Deploy the server on a remote machine
  • Build a GUI client using Tkinter or PyQt


Frequently Asked Questions


Is this chat app usable over the internet?

No. This project runs on localhost and is intended for learning networking basics.

Is this suitable for beginners?

This is best suited for intermediate learners who understand Python basics.



← Back to Projects