-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.py
More file actions
126 lines (108 loc) · 4.37 KB
/
Server.py
File metadata and controls
126 lines (108 loc) · 4.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
"""
-------------------------------------------------------
Server.
-------------------------------------------------------
Author: Daniyal Naqvi & Omar Hamza
ID: 169057430 & 169073034
Email: naqv7430@wlu.ca & hamz3034@wlu.ca
__updated__ = "2025-10-20"
-------------------------------------------------------
"""
#Imports
import socket
import threading
import os
from datetime import datetime
# Server Configuration
HOST = '127.0.0.1' # Localhost
PORT = 12345 # Port
MAX_CLIENTS = 3 # Max clients that are allowed
REPO_DIR = os.path.join(os.path.dirname(__file__), 'server_list') # Folder where files are stored
# Global Variables
client_cache = {} # Stores the clients connection info
client_count = 0 # Number of the connected clients
lock = threading.Lock() # Makes sure the thread-safe updates
# Handle Client Connection
def handle_client(conn, addr, client_name):
global client_count
#Prints the connection/disconnection with the clients name and time of connection
print(f"[NEW CONNECTION] {client_name} connected from {addr}")
client_cache[client_name] = {
'connected': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
'disconnected': None
}
#Try except to make sure program doesn't crash
try:
while True:
msg = conn.recv(1024).decode() # Receive the message from the client
if not msg:
break #Break when client disconnects
#Breaks when client exits
if msg.lower() == 'exit':
conn.send("Goodbye!".encode())
break
#Shows the status of the connections
elif msg.lower() == 'status':
# Return current client cache
status_info = "\n".join([f"{c}: {v}" for c, v in client_cache.items()])
conn.send(status_info.encode())
#Shows the list of files in the server_list
elif msg.lower() == 'list':
print(f"[DEBUG] 'list' command received from {client_name}")
#Checks if the file path exisits in the repository
if not os.path.exists(REPO_DIR):
conn.send("Repository folder not found!".encode())
else:
files = os.listdir(REPO_DIR)
print("[DEBUG] Files in repo:", files)
if not files:
conn.send("No files found in repository.".encode())
else:
conn.send("\n".join(files).encode())
elif os.path.isfile(os.path.join(REPO_DIR, msg)):
# Sends the file data to the client
with open(os.path.join(REPO_DIR, msg), 'rb') as f:
data = f.read()
conn.sendall(data)
print(f"[FILE SENT] {msg} sent to {client_name}")
else:
#Print ACK after the clients message
conn.send((msg + " ACK").encode())
except Exception as e:
print(f"[ERROR] Connection with {client_name} ended unexpectedly: {e}")
finally:
#Disconnect
conn.close()
print(f"[DISCONNECTED] {client_name}")
with lock:
client_cache[client_name]['disconnected'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
client_count -= 1
# -----------------------------
# Start the Server
# -----------------------------
def start_server():
global client_count
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen()
print(f"[LISTENING] Server running on {HOST}:{PORT}")
while True:
conn, addr = server.accept()
with lock:
if client_count >= MAX_CLIENTS:
# Reject extra clients
conn.send("Server full. Try again later.".encode())
print(f"[REJECTED CONNECTION] from {addr} — server full")
conn.close()
continue
# Accept new client
client_count += 1
client_name = f"Client{client_count:02d}"
# Start a new thread for the client
thread = threading.Thread(target=handle_client, args=(conn, addr, client_name))
thread.start()
# Run the Server
if __name__ == "__main__":
#Print a starting line for clarity
print("[STARTING] Server is starting...")
start_server()