Skip to content

Commit d5fd9f2

Browse files
authored
Merge pull request larymak#365 from AHNAF14924/main
Multi User Chat Application
2 parents c3e0965 + 499bfd3 commit d5fd9f2

File tree

3 files changed

+210
-0
lines changed

3 files changed

+210
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# Overview
2+
The **Multi-User Chat Application** is a Python-based chat application designed to provide real-time text-based communication among multiple users.
3+
4+
# Features
5+
The chat application includes the following key features:
6+
* **User Nicknames:** Users can set and display personalized nicknames within the chat.
7+
* **Private Messaging:** Users can send private messages to specific recipients.
8+
* **Message Logging:** All chat messages are logged on the server for historical reference.
9+
* **Error Handling:** The application handles various error scenarios for a stable user experience.
10+
11+
# Technologies Used
12+
The project was implemented using the following technologies:
13+
* **Python:** The primary programming language used for both the server and client applications.
14+
* **Python's socket library:** Utilized for network communication between the server and clients.
15+
* **Threading:** Implemented to enable concurrent handling of multiple client connections on the server.
16+
17+
# Installation and Usage
18+
To install and use the chat application, follow these steps:
19+
* Clone the project repository from [GitHub URL](https://github.com/AHNAF14924/Multi-User-Chat-Application.git)
20+
* Open the terminal/command prompt.
21+
* Navigate to the project directory.
22+
* Start the server by running python `server.py`
23+
* Run the client by executing python `client.py`
24+
## Server Setup
25+
* Choose one of the computers to act as the server. This computer will run the server code.
26+
* Modify the server code to use the computer's local IP address (e.g., '192.168.x.x' or '10.0.x.x') in the host variable. This allows other computers to connect to the server.
27+
* Run the server code on the chosen computer.
28+
29+
Example server code (change 'host' to the local IP address):
30+
31+
```
32+
host = '192.168.x.x' # Use the local IP address of the server computer
33+
port = 12345 # You can keep the same port
34+
```
35+
Start the server:
36+
```
37+
python3 server.py
38+
```
39+
## Client Setup
40+
* On each of the other computers, you will run the client code.
41+
* Modify the client code to use the IP address of the computer running the server in the server_host variable.
42+
* Run the client code on each computer.
43+
44+
Example client code (change 'server_host' to the server's IP address):
45+
```
46+
server_host = '192.168.x.x' # Use the server's local IP address
47+
server_port = 12345 # Keep the same port as the server
48+
```
49+
Start the client on each computer:
50+
51+
```
52+
python3 client.py
53+
```
54+
## Join the Chat
55+
56+
* After starting the client on each computer, you will be prompted to set a nickname. Enter a unique nickname for each user.
57+
* Once the nickname is set, you can start sending messages by typing in the terminal of each client. Messages will be sent to the server and broadcast to all connected clients.
58+
59+
## Sending Messages
60+
61+
* To send a regular message, type your message and press Enter. It will be broadcast to all connected clients.
62+
* To send a private message to a specific user, use the "@" symbol followed by the recipient's nickname, a space, and your message. For example: `@JohnDoe Hi, John!`
63+
64+
## Exiting the Application
65+
To exit the chat application:
66+
* Type `exit` in the terminal and press Enter. This will disconnect you from the chat and close the client application.
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import tkinter as tk
2+
from tkinter import scrolledtext
3+
import threading
4+
import socket
5+
6+
# Create a socket
7+
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
8+
9+
# Define the server's host and port
10+
server_host = '192.168.0.11' # Change this to the server's IP or hostname
11+
server_port = 12345
12+
13+
# Connect to the server
14+
client.connect((server_host, server_port))
15+
16+
# Function to send a message
17+
def send_message():
18+
message = message_entry.get()
19+
client.send(message.encode('utf-8'))
20+
message_entry.delete(0, tk.END)
21+
chat_text.config(state=tk.NORMAL)
22+
chat_text.insert(tk.END, "You: " + message + "\n")
23+
chat_text.config(state=tk.DISABLED)
24+
25+
# Function to receive and display messages from the server
26+
def receive_messages():
27+
while True:
28+
try:
29+
message = client.recv(1024).decode('utf-8')
30+
chat_text.config(state=tk.NORMAL)
31+
if message.startswith("Server: "):
32+
chat_text.insert(tk.END, message + "\n")
33+
else:
34+
chat_text.insert(tk.END, message + "\n")
35+
chat_text.config(state=tk.DISABLED)
36+
except:
37+
print("Connection closed.")
38+
client.close()
39+
break
40+
41+
# Create a GUI for the client
42+
client_gui = tk.Tk()
43+
client_gui.title("Chat Client")
44+
45+
chat_text = scrolledtext.ScrolledText(client_gui, wrap=tk.WORD)
46+
chat_text.config(state=tk.DISABLED)
47+
chat_text.pack()
48+
49+
message_entry = tk.Entry(client_gui)
50+
message_entry.pack()
51+
52+
send_button = tk.Button(client_gui, text="Send", command=send_message)
53+
send_button.pack()
54+
55+
# Create a thread to receive messages
56+
receive_thread = threading.Thread(target=receive_messages)
57+
receive_thread.start()
58+
59+
# Main GUI loop
60+
client_gui.mainloop()
61+
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
import socket
2+
import threading
3+
4+
# Create a socket
5+
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
6+
7+
# Define the host and port
8+
host = '192.168.0.11' # Listen on all available network interfaces
9+
port = 12345
10+
11+
# Bind the socket to the host and port
12+
server.bind((host, port))
13+
14+
# Listen for incoming connections
15+
server.listen()
16+
17+
print(f"Server listening on {host}:{port}")
18+
19+
# Store client connections and nicknames in dictionaries
20+
clients = {}
21+
nicknames = {}
22+
23+
# Function to broadcast messages to all connected clients
24+
def broadcast(message, sender=None):
25+
for client_socket, nickname in zip(clients, nicknames):
26+
if client_socket != sender:
27+
try:
28+
client_socket.send(message.encode('utf-8'))
29+
except:
30+
remove_client(client_socket)
31+
32+
# Function to handle client connections
33+
def handle_client(client_socket):
34+
try:
35+
# Request and store the user's nickname
36+
client_socket.send("Enter your nickname: ".encode('utf-8'))
37+
nickname = client_socket.recv(1024).decode('utf-8')
38+
nicknames[client_socket] = nickname
39+
print(f"Nickname of {nickname} is set.")
40+
41+
# Welcome message
42+
welcome_message = f"Welcome, {nickname}!"
43+
client_socket.send(welcome_message.encode('utf-8'))
44+
45+
while True:
46+
message = client_socket.recv(1024)
47+
if not message:
48+
remove_client(client_socket)
49+
break
50+
elif message.decode('utf-8').lower() == 'exit':
51+
remove_client(client_socket)
52+
elif message.decode('utf-8').startswith('@'):
53+
# Private message
54+
recipient = message.decode('utf-8').split(' ')[0][1:]
55+
if recipient in nicknames.values():
56+
recipient_socket = list(nicknames.keys())[list(nicknames.values()).index(recipient)]
57+
recipient_socket.send(f"(Private) {nickname}: {message.decode('utf-8')[len(recipient) + 2:]}".encode('utf-8'))
58+
else:
59+
client_socket.send("Recipient not found.".encode('utf-8'))
60+
else:
61+
# Broadcast regular message
62+
broadcast(f"{nickname}: {message.decode('utf-8')}", sender=client_socket)
63+
except:
64+
remove_client(client_socket)
65+
66+
# Function to remove a client from the server
67+
def remove_client(client_socket):
68+
if client_socket in clients:
69+
print(f"Connection closed with {nicknames[client_socket]}")
70+
del nicknames[client_socket]
71+
clients.pop(client_socket)
72+
client_socket.close()
73+
74+
# Main server loop
75+
while True:
76+
client_socket, client_address = server.accept()
77+
print(f"Accepted connection from {client_address}")
78+
clients[client_socket] = client_address
79+
80+
# Start a thread to handle the client
81+
client_thread = threading.Thread(target=handle_client, args=(client_socket,))
82+
client_thread.start()
83+

0 commit comments

Comments
 (0)