python编写TCP程序,由客户端发送正整数n,服务端计算n!并返回。
时间: 2024-05-14 21:17:40 浏览: 78
下面是一个简单的Python TCP客户端/服务器程序,实现客户端发送正整数n,服务端计算n!并返回:
服务端代码:
```python
import socket
import math
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
def main():
HOST = '127.0.0.1' # 监听的IP地址
PORT = 8888 # 监听的端口号
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
print('Server is listening on %s:%s...' % (HOST, PORT))
while True:
conn, addr = s.accept()
print('Connected by', addr)
data = conn.recv(1024)
if not data:
break
n = int(data)
print('Received number:', n)
result = factorial(n)
conn.sendall(str(result).encode())
conn.close()
if __name__ == '__main__':
main()
```
客户端代码:
```python
import socket
def main():
HOST = '127.0.0.1' # 服务器的IP地址
PORT = 8888 # 服务器的端口号
n = int(input('Enter a positive integer: '))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall(str(n).encode())
data = s.recv(1024)
print('Factorial of %d is %s' % (n, data.decode()))
s.close()
if __name__ == '__main__':
main()
```
运行服务端程序后,可以看到输出:
```
Server is listening on 127.0.0.1:8888...
```
然后运行客户端程序,输入一个正整数n,程序会自动连接到服务端,并将n发送给服务端。服务端计算n!,并将结果返回给客户端。客户端接收到结果后,打印出来。例如,输入5,会得到输出:
```
Enter a positive integer: 5
Factorial of 5 is 120
```
阅读全文