server.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import socket
  2. import json
  3. # Define the host and port on which the server will listen
  4. host = "127.0.0.1"
  5. port = 29989
  6. # Create a socket object
  7. server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  8. # Bind the socket to a specific address and port
  9. server_socket.bind((host, port))
  10. # Listen for incoming connections
  11. server_socket.listen()
  12. print(f"Server listening on {host}:{port}")
  13. def handle_client(client_socket):
  14. while True:
  15. # Receive data from the client
  16. client_data = client_socket.recv(1024).decode('utf-8')
  17. if not client_data:
  18. print("Connection closed.")
  19. break
  20. print(f"Client data: {client_data}")
  21. # Prepare JSON response data
  22. response_data = {"code": "ok"}
  23. response_json = json.dumps(response_data)
  24. # Send the JSON response back to the client
  25. client_socket.send(response_json.encode('utf-8'))
  26. def start():
  27. while True:
  28. # Wait for a connection from a client
  29. client_socket, client_address = server_socket.accept()
  30. print(f"Connection from {client_address}")
  31. # Handle the client in a separate function
  32. handle_client(client_socket)
  33. if __name__ == "__main__":
  34. start()