Chat App (Sockets) in Python.
About the project: This is a project for a Simple Chat App that uses sockets for real-time communication in Python.
It is the project that's more advanced than a basic CLI simulation.
Finally, it will move the files into their corresponding folders, making your directory much neater.
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 to use this program:
To use this simple chat application, you need to run both scripts.
- 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.
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.
Steps: Follow these stepsStep 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()