-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathserver.py
40 lines (32 loc) · 1.13 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
import socket
def sendfile(client_socket, filename):
try:
with open(filename, 'rb') as file:
chunk = file.read(1024)
while chunk:
client_socket.send(chunk)
chunk = file.read(1024)
client_socket.send(b'EOF') # Send end-of-file marker
except FileNotFoundError:
error_message = f"Error: File '{filename}' not found."
print(error_message)
client_socket.send(bytes(error_message, "utf-8"))
except Exception as e:
print(f"An error occurred: {e}")
def main():
# Server setup
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 1234))
s.listen(5)
print("Server is listening...")
while True:
clientsocket, address = s.accept()
print(f"Connection from {address} has been established!")
# Receive filename from client
filename = clientsocket.recv(1024).decode('utf-8')
print(f"Client requested file: {filename}")
# Send file
sendfile(clientsocket, filename)
clientsocket.close()
if __name__ == "__main__":
main()