将下列代码用进程或线程的方式改写while True: print('等待客户连接...\r\n'); cs,caddr=ss.accept() print('连接来自于:',caddr) data='欢迎你的到来!\r\n' cs.sendall(bytes(data,'utf-8')) data=cs.recv(1024).decode('utf-8') if not data: break print('三角形三边长为:',data) sides=data.split(',') cs.sendall(bytes(''+str(triangle(float(sides[0]), float(sides[1]),float(sides[2]))),'utf-8')) cs.close() ss.close() from socket import * s=socket(AF_INET,SOCK_STREAM,0) s.connect(('127.0.0.1',5005)) data=s.recv(1024).decode('utf-8') if data: print(data) a=input("请输入边长a:") b=input("请输入边长b:") c=input("请输入边长c:") data=a+','+b+','+c if data: s.sendall(bytes(data,'utf-8')) data=s.recv(1024).decode('utf-8') if data: print('三角形面积为:',data) s.close()
时间: 2024-01-03 17:03:36 浏览: 130
使用线程方式改写:
```python
import threading
from socket import *
def handle_client(cs):
print('连接来自于:', cs.getpeername())
data = '欢迎你的到来!\r\n'
cs.sendall(bytes(data, 'utf-8'))
data = cs.recv(1024).decode('utf-8')
if not data:
return
print('三角形三边长为:', data)
sides = data.split(',')
cs.sendall(bytes('' + str(triangle(float(sides[0]), float(sides[1]), float(sides[2]))), 'utf-8'))
cs.close()
def client_thread():
s = socket(AF_INET, SOCK_STREAM, 0)
s.connect(('127.0.0.1', 5005))
data = s.recv(1024).decode('utf-8')
if data:
print(data)
a = input("请输入边长a:")
b = input("请输入边长b:")
c = input("请输入边长c:")
data = a + ',' + b + ',' + c
if data:
s.sendall(bytes(data, 'utf-8'))
data = s.recv(1024).decode('utf-8')
if data:
print('三角形面积为:', data)
s.close()
ss = socket(AF_INET, SOCK_STREAM, 0)
ss.bind(('127.0.0.1', 5005))
ss.listen(5)
print('等待客户连接...\r\n')
while True:
cs, caddr = ss.accept()
thread = threading.Thread(target=handle_client, args=(cs,))
thread.start()
client_thread()
```
使用进程方式改写:
```python
import multiprocessing
from socket import *
def handle_client(cs):
print('连接来自于:', cs.getpeername())
data = '欢迎你的到来!\r\n'
cs.sendall(bytes(data, 'utf-8'))
data = cs.recv(1024).decode('utf-8')
if not data:
return
print('三角形三边长为:', data)
sides = data.split(',')
cs.sendall(bytes('' + str(triangle(float(sides[0]), float(sides[1]), float(sides[2]))), 'utf-8'))
cs.close()
def client_process():
s = socket(AF_INET, SOCK_STREAM, 0)
s.connect(('127.0.0.1', 5005))
data = s.recv(1024).decode('utf-8')
if data:
print(data)
a = input("请输入边长a:")
b = input("请输入边长b:")
c = input("请输入边长c:")
data = a + ',' + b + ',' + c
if data:
s.sendall(bytes(data, 'utf-8'))
data = s.recv(1024).decode('utf-8')
if data:
print('三角形面积为:', data)
s.close()
ss = socket(AF_INET, SOCK_STREAM, 0)
ss.bind(('127.0.0.1', 5005))
ss.listen(5)
print('等待客户连接...\r\n')
while True:
cs, caddr = ss.accept()
process = multiprocessing.Process(target=handle_client, args=(cs,))
process.start()
client_process()
```
阅读全文