您好,登录后才能下订单哦!
server端
import sys,socket,time,gevent
from gevent import socket, monkey
monkey.patch_all()#卡住每个进程
def server(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阻塞就切换
def handle_request(conn):# 类似socketserver的handle方法
try:
while True:
data = conn.recv(1024)
print("recv:", data)
conn.send(data)
if not data:
break #关闭客户端
except Exception as ex:#打印异常
print(ex)
finally:
conn.close()
if __name__ == '__main__':
server(8001)
client端
import socket
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 not msg:continue #输入为空 跳出循环又从第1行开始循环
s.sendall(msg)
data = s.recv(1024)
# print(data)
print('Received', repr(data))#repr格式化输出
s.close()
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。