tcp_server.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import socketserver
  2. import os
  3. class MyHandler(socketserver.BaseRequestHandler):
  4. def handle(self):
  5. print("Connection received from:", self.client_address)
  6. try:
  7. # Receive file path length
  8. path_len_bytes = self.request.recv(8)
  9. if not path_len_bytes:
  10. print("Error receiving file path length.")
  11. return
  12. path_len = int.from_bytes(path_len_bytes, byteorder='little') # Change byte order to 'little'
  13. print(f"Received file path length: {path_len}")
  14. # Receive file path
  15. file_path_bytes = b""
  16. while len(file_path_bytes) < path_len:
  17. received_data = self.request.recv(path_len - len(file_path_bytes))
  18. if not received_data:
  19. print("Error receiving file path.")
  20. return
  21. file_path_bytes += received_data
  22. file_name = file_path_bytes.decode('utf-8')
  23. print("Received file name:", file_name)
  24. # Check if the file exists
  25. file_path = os.path.join(os.getcwd(), file_name)
  26. print("Absolute file path:", file_path)
  27. if os.path.exists(file_path):
  28. print("File found:", file_path)
  29. # Read file data
  30. with open(file_path, 'rb') as file:
  31. file_data = file.read()
  32. # Print the size before sending
  33. file_size = len(file_data)
  34. print("Size of file:", file_size)
  35. # Send file size to the client
  36. self.request.sendall(file_size.to_bytes(4, byteorder='big'))
  37. # Send file data back to the client
  38. self.request.sendall(file_data)
  39. print("File data sent successfully.")
  40. else:
  41. print("File not found:", file_path)
  42. self.request.sendall(b"FILE_NOT_FOUND")
  43. except Exception as e:
  44. print("Error:", str(e))
  45. self.request.sendall(b"SERVER_ERROR")
  46. if __name__ == "__main__":
  47. host, port = "192.168.1.12", 8080
  48. server = socketserver.TCPServer((host, port), MyHandler)
  49. print(f"Server listening on {host}:{port}")
  50. try:
  51. server.serve_forever()
  52. except KeyboardInterrupt:
  53. print("Server shutting down.")
  54. server.shutdown()