使用套接字连接编写一个网络程序,用户在客户端输入三角形的3条边长,客户端将他们发送给服务器端,服务器吧计算出的三角形的面积返回给客户端,客户端命令行窗口中显示面积值
时间: 2023-12-03 11:46:56 浏览: 88
以下是使用 Python 编写的客户端和服务器端代码:
### 服务器端代码
```python
import socket
def calc_area(a, b, c):
s = (a + b + c) / 2
area = (s * (s-a) * (s-b) * (s-c)) ** 0.5
return area
def main():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 8000))
server_socket.listen(1)
print('Server is listening on port 8000...')
while True:
conn, addr = server_socket.accept()
print('Connected by', addr)
data = conn.recv(1024)
if not data:
break
sides = data.decode().split(',')
a, b, c = float(sides[0]), float(sides[1]), float(sides[2])
area = calc_area(a, b, c)
conn.sendall(str(area).encode())
print(f'Triangle with sides {a}, {b}, {c} has area {area}')
conn.close()
if __name__ == '__main__':
main()
```
### 客户端代码
```python
import socket
def main():
server_addr = ('localhost', 8000)
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(server_addr)
a = input('Enter side 1: ')
b = input('Enter side 2: ')
c = input('Enter side 3: ')
sides = ','.join([a, b, c])
client_socket.sendall(sides.encode())
data = client_socket.recv(1024)
print(f'The area of the triangle is {data.decode()}')
client_socket.close()
if __name__ == '__main__':
main()
```
客户端程序会提示用户输入三角形的三条边长,然后将它们转换为以逗号分隔的字符串发送给服务器端。服务器端接收到数据后会计算三角形的面积,并将结果发送回客户端。客户端程序会显示服务器端返回的面积值。
阅读全文