Basic Chatroom App
Abstract
Basic Chatroom App is a Python project that enables real-time text communication between multiple users over a network. It demonstrates socket programming, threading, and basic GUI development. This project is ideal for learning about client-server architecture, concurrency, and event-driven programming.
Prerequisites
- Python 3.6 or above
- socket, threading (built-in)
- tkinter (for GUI, usually pre-installed)
Before you Start
Ensure Python is installed. No external packages are required. For GUI, make sure Tkinter is available.
Getting Started
- Create a folder named
chatroom-app
chatroom-app
. - Create a file named
basic_chatroom_app.py
basic_chatroom_app.py
. - Copy the code below into your file.
⚙️ Basic Chatroom App
Basic Chatroom App
"""
Basic Chatroom App
A Python application that allows multiple users to communicate in a chatroom.
Features include:
- Server-side implementation to manage multiple clients.
- Client-side implementation for sending and receiving messages.
"""
import socket
import threading
# Server-side implementation
class ChatServer:
def __init__(self, host="localhost", port=12345):
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.bind((host, port))
self.server.listen(5)
print(f"Server started on {host}:{port}")
self.clients = []
def broadcast(self, message, client_socket):
"""Send a message to all connected clients except the sender."""
for client in self.clients:
if client != client_socket:
try:
client.send(message)
except:
self.clients.remove(client)
def handle_client(self, client_socket):
"""Handle communication with a connected client."""
while True:
try:
message = client_socket.recv(1024)
if message:
print(f"Received: {message.decode('utf-8')}")
self.broadcast(message, client_socket)
except:
self.clients.remove(client_socket)
client_socket.close()
break
def run(self):
"""Start the server and accept incoming connections."""
while True:
client_socket, client_address = self.server.accept()
print(f"New connection: {client_address}")
self.clients.append(client_socket)
threading.Thread(target=self.handle_client, args=(client_socket,)).start()
# Client-side implementation
class ChatClient:
def __init__(self, host="localhost", port=12345):
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.client.connect((host, port))
threading.Thread(target=self.receive_messages).start()
def send_message(self, message):
"""Send a message to the server."""
self.client.send(message.encode("utf-8"))
def receive_messages(self):
"""Receive messages from the server."""
while True:
try:
message = self.client.recv(1024).decode("utf-8")
print(message)
except:
print("Disconnected from server.")
self.client.close()
break
if __name__ == "__main__":
choice = input("Do you want to start the server or client? (server/client): ").strip().lower()
if choice == "server":
server = ChatServer()
server.run()
elif choice == "client":
client = ChatClient()
print("Type your messages below:")
while True:
msg = input()
client.send_message(msg)
else:
print("Invalid choice. Exiting.")
Basic Chatroom App
"""
Basic Chatroom App
A Python application that allows multiple users to communicate in a chatroom.
Features include:
- Server-side implementation to manage multiple clients.
- Client-side implementation for sending and receiving messages.
"""
import socket
import threading
# Server-side implementation
class ChatServer:
def __init__(self, host="localhost", port=12345):
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.bind((host, port))
self.server.listen(5)
print(f"Server started on {host}:{port}")
self.clients = []
def broadcast(self, message, client_socket):
"""Send a message to all connected clients except the sender."""
for client in self.clients:
if client != client_socket:
try:
client.send(message)
except:
self.clients.remove(client)
def handle_client(self, client_socket):
"""Handle communication with a connected client."""
while True:
try:
message = client_socket.recv(1024)
if message:
print(f"Received: {message.decode('utf-8')}")
self.broadcast(message, client_socket)
except:
self.clients.remove(client_socket)
client_socket.close()
break
def run(self):
"""Start the server and accept incoming connections."""
while True:
client_socket, client_address = self.server.accept()
print(f"New connection: {client_address}")
self.clients.append(client_socket)
threading.Thread(target=self.handle_client, args=(client_socket,)).start()
# Client-side implementation
class ChatClient:
def __init__(self, host="localhost", port=12345):
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.client.connect((host, port))
threading.Thread(target=self.receive_messages).start()
def send_message(self, message):
"""Send a message to the server."""
self.client.send(message.encode("utf-8"))
def receive_messages(self):
"""Receive messages from the server."""
while True:
try:
message = self.client.recv(1024).decode("utf-8")
print(message)
except:
print("Disconnected from server.")
self.client.close()
break
if __name__ == "__main__":
choice = input("Do you want to start the server or client? (server/client): ").strip().lower()
if choice == "server":
server = ChatServer()
server.run()
elif choice == "client":
client = ChatClient()
print("Type your messages below:")
while True:
msg = input()
client.send_message(msg)
else:
print("Invalid choice. Exiting.")
- Run the server and client scripts as described in the code comments.
Explanation
Code Breakdown
- Import modules
import socket
import threading
import tkinter as tk
import socket
import threading
import tkinter as tk
- Server setup
def start_server():
# Accepts connections and relays messages
pass
def start_server():
# Accepts connections and relays messages
pass
- Client setup
def start_client():
# Connects to server and sends/receives messages
pass
def start_client():
# Connects to server and sends/receives messages
pass
- GUI for chat
root = tk.Tk()
root.title('Chatroom')
# ...setup widgets for chat display and input...
root.mainloop()
root = tk.Tk()
root.title('Chatroom')
# ...setup widgets for chat display and input...
root.mainloop()
Features
- Real-time text chat
- Multiple users
- Simple GUI
- Demonstrates sockets and threading
How It Works
- Server listens for connections
- Clients connect and send messages
- Messages are broadcast to all clients
- GUI displays chat and allows input
GUI Components
- Text area: Shows chat history
- Entry box: For message input
- Send button: Sends message
Use Cases
- Learn networking basics
- Build simple chat apps
- Experiment with concurrency
Next Steps
You can enhance this project by:
- Adding user authentication
- Supporting private messages
- Improving GUI design
- Adding emojis or file sharing
- Implementing message history
Enhanced Version Ideas
def add_authentication():
# Require login for chat
pass
def save_chat_history():
# Store messages in a file
pass
def add_authentication():
# Require login for chat
pass
def save_chat_history():
# Store messages in a file
pass
Troubleshooting Tips
- Connection errors: Check IP and port
- GUI not showing: Ensure Tkinter is installed
- Messages not sent: Check server/client status
Conclusion
This project teaches networking, threading, and GUI basics. Extend it for more features and better user experience.
Was this page helpful?
Let us know how we did