通过网络编程实现客户端与服务器端程序设计,客户端发出一个数值,服务器端计算圆的面积并返回给客户端,请讲程序代码和运行结果截图上交。
时间: 2024-11-04 07:11:03 浏览: 27
在网络编程中,通常使用TCP/IP协议栈来实现实时通信。这里是一个简单的Python示例,展示了客户端如何发送一个数值到服务器,服务器计算圆的面积并返回结果。请注意,由于这是一个文本环境,我无法提供实际的运行结果截图。
**服务器端代码 (server.py)**:
```python
import socket
def calculate_circle_area(radius):
area = 3.14 * radius ** 2
return f"Circle area for {radius} is {area}"
def main():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 12345))
server_socket.listen(1)
while True:
client_connection, addr = server_socket.accept()
request_data = client_connection.recv(1024).decode('utf-8')
radius = float(request_data)
response = calculate_circle_area(radius)
client_connection.sendall(response.encode('utf-8'))
client_connection.close()
if __name__ == "__main__":
main()
```
**客户端代码 (client.py)**:
```python
import socket
def send_request(radius):
try:
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 12345))
client_socket.sendall(str(radius).encode('utf-8'))
received_data = client_socket.recv(1024).decode('utf-8')
print(f"Received: {received_data}")
client_socket.close()
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
radius = input("Enter the radius of the circle: ")
send_request(radius)
```
运行客户端,输入圆的半径,然后服务器会计算并返回圆的面积。例如,如果输入半径为`5`,预期结果可能是`Received: Circle area for 5.0 is 78.5`。
阅读全文