1.分别开发TCP客户端与服务端,客户端从键盘输入一个四则运算表达式(如“1+2”、“6/3”等)并发送给服务端。服务端接收后执行运行,并将结果返回给客户端。详见参考代码。
时间: 2024-06-13 20:09:20 浏览: 73
C# 实现 TCP服务端+客户端 带心跳机制.zip
以下是Python实现TCP客户端与服务端,客户端从键盘输入一个四则运算表达式并发送给服务端,服务端接收后执行运算,并将结果返回给客户端的代码:
服务端代码:
```python
import socket
def calculate(expression):
try:
result = eval(expression)
return str(result)
except:
return "Error: Invalid expression"
HOST = '127.0.0.1'
PORT = 8888
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen(1)
print('Server is running on %s:%s' % (HOST, PORT))
while True:
conn, addr = server_socket.accept()
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
expression = data.decode()
print('Received expression:', expression)
result = calculate(expression)
conn.sendall(result.encode())
conn.close()
print('Connection closed')
```
客户端代码:
```python
import socket
HOST = '127.0.0.1'
PORT = 8888
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))
while True:
expression = input('Please enter an expression (q to quit): ')
if expression == 'q':
break
client_socket.sendall(expression.encode())
result = client_socket.recv(1024).decode()
print('Result:', result)
client_socket.close()
```
阅读全文