-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
59 lines (46 loc) · 1.71 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
import os
import socket
IP = socket.gethostbyname(socket.gethostname())
PORT = 4455
ADDR = (IP, PORT)
FORMAT = 'utf-8'
SIZE = 8
SERVER_FOLDER = 'server_data'
DIR = 'server_data'
def main():
"""
* Main function that initiates a TCP socket, binds the server and receives filenames from client
* in order to send the corresponding files from the DIR = 'server_data' directory.
"""
""" Staring a TCP socket. """
print("[STARTING] Server is starting.")
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
""" Bind the IP and PORT to the server. """
server.bind(ADDR)
""" Server is listening, i.e., server is now waiting for the client to connected. """
server.listen()
print("[LISTENING] Server is listening.")
while True:
""" Server has accepted the connection from the client. """
conn, addr = server.accept()
print(f"[NEW CONNECTION] {addr} connected.")
while True:
try:
""" Receiving the filename from the client. """
filename = conn.recv(SIZE).decode(FORMAT)
if not filename:
break
print(f"[RECV] Requested {filename}.")
""" Sending file to client """
file_path = os.path.join(DIR, filename)
with open(file_path, "rb") as file:
data = file.read()
data += b'2e51b1ab42e8a4a67f3445174be5191b'
conn.sendall(data)
print(f'[SERVER] File {filename} sent.')
except ConnectionError:
break
print(f"[CLOSING CONNECTION] {addr} closed.")
conn.close()
if __name__ == '__main__':
main()