-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathserver.py
86 lines (69 loc) · 2.57 KB
/
server.py
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
import os
import socket
import threading
IP = socket.gethostbyname(socket.gethostname())
PORT = 4456
ADDR = (IP, PORT)
SIZE = 1024
FORMAT = "utf-8"
SERVER_DATA_PATH = "server_data"
def handle_client(conn, addr):
print(f"[NEW CONNECTION] {addr} connected.")
conn.send("OK@Welcome to the File Server.".encode(FORMAT))
while True:
data = conn.recv(SIZE).decode(FORMAT)
data = data.split("@")
cmd = data[0]
if cmd == "LIST":
files = os.listdir(SERVER_DATA_PATH)
send_data = "OK@"
if len(files) == 0:
send_data += "The server directory is empty"
else:
send_data += "\n".join(f for f in files)
conn.send(send_data.encode(FORMAT))
elif cmd == "UPLOAD":
name, text = data[1], data[2]
filepath = os.path.join(SERVER_DATA_PATH, name)
with open(filepath, "w") as f:
f.write(text)
send_data = "OK@File uploaded successfully."
conn.send(send_data.encode(FORMAT))
elif cmd == "DELETE":
files = os.listdir(SERVER_DATA_PATH)
send_data = "OK@"
filename = data[1]
if len(files) == 0:
send_data += "The server directory is empty"
else:
if filename in files:
os.system(f"rm {SERVER_DATA_PATH}/{filename}")
send_data += "File deleted successfully."
else:
send_data += "File not found."
conn.send(send_data.encode(FORMAT))
elif cmd == "LOGOUT":
break
elif cmd == "HELP":
data = "OK@"
data += "LIST: List all the files from the server.\n"
data += "UPLOAD <path>: Upload a file to the server.\n"
data += "DELETE <filename>: Delete a file from the server.\n"
data += "LOGOUT: Disconnect from the server.\n"
data += "HELP: List all the commands."
conn.send(data.encode(FORMAT))
print(f"[DISCONNECTED] {addr} disconnected")
conn.close()
def main():
print("[STARTING] Server is starting")
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
server.listen()
print(f"[LISTENING] Server is listening on {IP}:{PORT}.")
while True:
conn, addr = server.accept()
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")
if __name__ == "__main__":
main()