服务端
from socket import * import select server = socket(AF_INET, SOCK_STREAM) server.bind(('127.0.0.1',8083)) server.listen(5) server.setblocking(False) print('starting...') rlist=[server,] #收消息套接字列表 wlist=[] #发消息套接字列表 wdata={} while True: rl,wl,xl=select.select(rlist,wlist,[],0.5) #rl(可以收的套接字),wl(发的套接字),xl(出异常的套接字) print('rl',rl) print('wl',wl) for sock in rl: if sock == server: #如果有server类型的链接进来就建链接并把套掉字加到rlist列表里 conn,addr=sock.accept() rlist.append(conn) else: #如果不是server类弄的链接,那就是conn类型,就可以收数据了 try: data=sock.recv(1024) if not data: #如果是linux系统,客户断开不会抛异常,发空情况rlist.remove(sock) sock.close() rlist.remove(sock) continue wlist.append(sock) wdata[sock]=data.upper() except Exception: #如果客户端主动断开,rlist.remove(sock) sock.close() rlist.remove(sock) #发消息 for sock in wl: data=wdata[sock] sock.send(data) wlist.remove(sock) wdata.pop(sock) server.close()
客户端
from socket import * client=socket(AF_INET,SOCK_STREAM) client.connect(('127.0.0.1',8083)) 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()