server端
importsys,socket,time,gevent
fromgeventimportsocket, monkey
monkey.patch_all()#卡住每个进程
defserver(port):
s = socket.socket()
s.bind(('0.0.0.0', port))
s.listen(500)
while True:
cli, addr = s.accept()
gevent.spawn(handle_request, cli)#起协程 把cli连接传给handle_request遇到IO阻塞就切换
defhandle_request(conn):#类似socketserver的handle方法
try:
while True:
data = conn.recv(1024)
print("recv:", data)
conn.send(data)
if notdata:
break#关闭客户端
exceptException as ex:#打印异常
print(ex)
finally:
conn.close()
if__name__ =='__main__':
server(8001)
威远网站建设公司创新互联建站,威远网站设计制作,有大型网站制作公司丰富经验。已为威远上1000+提供企业网站建设服务。企业网站搭建\成都外贸网站建设要多少钱,请找那个售后服务好的威远做网站的公司定做!
client端
importsocket
HOST ='localhost' # The remote host
PORT =8001 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
while True:
msg =bytes(input(">>:"),encoding="utf8") #转成bytes类型
if notmsg:continue#输入为空 跳出循环又从第1行开始循环
s.sendall(msg)
data = s.recv(1024)
# print(data)
print('Received',repr(data))#repr格式化输出
s.close()