服务端
from socke import * server = socket(AF_INET, SOCK_STREAM) server.bind(('127.0.0.1',8083)) server.listen(5) server.setblocking(False) #1 print('starting...') rlist=[] #链接套接字加到rlist里 ["链接类型","协议","ip,port"] wlist=[] while True: try: conn, addr = server.accept() rlist.append(conn) print(rlist) except BlockingIOError: # 检测BlockingIOError # print('干其他的活') #收消息 del_rlist = [] for conn in rlist: #遍历套接字,有消息过来。就继续下一步, # 没消息过来就交conn添加到del_rlist,再去通过del_list列表remove掉rlist里的conn try: data=conn.recv(1024) if not data: del_rlist.append(conn) continue wlist.append((conn,data.upper())) except BlockingIOError: # 检测BlockingIOError continue except Exception: conn.close() del_rlist.append(conn) #发消息 del_wlist=[] for item in wlist: try: conn=item[0] data=item[1] conn.send(data) del_wlist.append(item) except BlockingIOError: pass for item in del_wlist: wlist.remove(item) for conn in del_rlist: rlist.remove(conn) server.close()
客户端
from socket import * client=socket(AF_INET,SOCK_STREAM) client.connect(('127.0.0.1',8080)) while True: msg=input('>>: ').strip() if not msg:continue client.send(msg.encode('utf-8')) data=client.recv(1024) print(data.decode('utf-8')) client.close()