编写TCP程序,由客户端发送正整数n,服务端计算n!并返回
时间: 2024-05-14 14:17:41 浏览: 29
以下是一个简单的TCP程序实现:
客户端代码:
```python
import socket
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
host = 'localhost'
port = 8888
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((host, port))
n = int(input("Enter a positive integer: "))
client_socket.send(str(n).encode())
result = client_socket.recv(1024).decode()
print("Factorial of", n, "is", result)
client_socket.close()
```
服务端代码:
```python
import socket
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
host = 'localhost'
port = 8888
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(1)
print("Listening for incoming connections...")
while True:
conn, addr = server_socket.accept()
print("Connection from:", addr)
data = conn.recv(1024).decode()
n = int(data)
result = factorial(n)
conn.send(str(result).encode())
conn.close()
```
运行服务端程序后,客户端程序可以通过输入一个正整数n,向服务端发送请求。服务端接收到请求后,计算n!并返回给客户端。客户端程序接收到结果后,输出n!的值。
阅读全文