12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- import socket
- import json
- # Define the host and port on which the server will listen
- host = "127.0.0.1"
- port = 29989
- # Create a socket object
- server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- # Bind the socket to a specific address and port
- server_socket.bind((host, port))
- # Listen for incoming connections
- server_socket.listen()
- print(f"Server listening on {host}:{port}")
- def handle_client(client_socket):
- while True:
- # Receive data from the client
- client_data = client_socket.recv(1024).decode('utf-8')
- if not client_data:
- print("Connection closed.")
- break
- print(f"Client data: {client_data}")
- # Prepare JSON response data
- response_data = {"code": "ok"}
- response_json = json.dumps(response_data)
- # Send the JSON response back to the client
- client_socket.send(response_json.encode('utf-8'))
- def start():
- while True:
- # Wait for a connection from a client
- client_socket, client_address = server_socket.accept()
- print(f"Connection from {client_address}")
- # Handle the client in a separate function
- handle_client(client_socket)
- if __name__ == "__main__":
- start()
|