Python TCP客户端-服务端通信:带参数斐波那契功能实现求助
Got it, let's break down how to add this parameterized Fibonacci feature to your TCP client-server setup. The core idea is defining a clear message protocol between client and server so they can understand both the function request and its arguments—something you didn't need for your earlier parameter-less functions.
1. Define a Simple Message Protocol
Since we need to send both a command and its parameters, JSON is the easiest, most robust choice here. It lets us package structured data into a string that’s easy to serialize and parse. Our protocol will look like this:
- Client sends:
{"command": "fibonacci", "params": {"n": 10}}(plus a newline to mark the end of the message, since TCP is a stream protocol) - Server responds with either a success message:
{"status": "success", "result": 55}or an error:{"status": "error", "message": "Invalid number"}
2. Server Implementation
Here’s how to modify your server to handle the parameterized Fibonacci request:
import socket import json # Your existing Fibonacci function def FIBONACCI(n): if n == 0: return 0 elif n == 1: return 1 else: return FIBONACCI(n-1) + FIBONACCI(n-2) def handle_client_connection(conn): try: # Receive and decode the client's message raw_data = conn.recv(1024).decode('utf-8').strip() if not raw_data: return # Parse the JSON request request = json.loads(raw_data) command = request.get('command') if command == 'fibonacci': # Extract and validate the parameter n = request.get('params', {}).get('n') if isinstance(n, int) and n >= 0: result = FIBONACCI(n) response = json.dumps({'status': 'success', 'result': result}) else: response = json.dumps({'status': 'error', 'message': 'Please enter a non-negative integer'}) else: response = json.dumps({'status': 'error', 'message': 'Unknown command'}) # Send the response back to the client conn.sendall((response + '\n').encode('utf-8')) except Exception as e: print(f"Error processing request: {str(e)}") finally: conn.close() def start_server(): host = '127.0.0.1' port = 65432 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket: server_socket.bind((host, port)) server_socket.listen() print(f"Server running on {host}:{port}") while True: conn, addr = server_socket.accept() with conn: print(f"Connected to client at {addr}") handle_client_connection(conn) if __name__ == "__main__": start_server()
3. Client Implementation
Now update your client to prompt for the Fibonacci number and send the structured request:
import socket import json def start_client(): host = '127.0.0.1' port = 65432 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket: client_socket.connect((host, port)) print("Connected to server!") # Show function menu print("\nAvailable Functions:") print("1. Calculate Fibonacci Number") choice = input("Enter your choice (1): ") if choice == '1': # Get valid input from user while True: try: n = int(input("Enter a non-negative integer: ")) if n < 0: print("Please enter a number greater than or equal to 0.") continue break except ValueError: print("Invalid input—please enter an integer.") # Build and send the JSON request request = json.dumps({ 'command': 'fibonacci', 'params': {'n': n} }) + '\n' # Newline marks end of message client_socket.sendall(request.encode('utf-8')) # Receive and parse the server's response raw_response = client_socket.recv(1024).decode('utf-8').strip() response = json.loads(raw_response) if response['status'] == 'success': print(f"Fibonacci({n}) = {response['result']}") else: print(f"Server Error: {response['message']}") else: print("Invalid choice—exiting.") if __name__ == "__main__": start_client()
Key Notes for Your Transition
- Message Delimiting: We added a newline (
\n) to each message because TCP sends data as a stream—this helps both sides know when a complete message ends. - Input Validation: We added checks for non-integer or negative inputs on both client and server to avoid crashes.
- Scalability: This pattern works for other parameterized functions too—just add more command cases in the server and update the client menu.
内容的提问来源于stack exchange,提问作者nor

