#!/usr/bin/env python#-*-coding:utf-8 -*-import socketsk=socket.socket()sk.connect(("127.0.0.1",8090))while 1: inp=input(">>>") sk.send(inp.encode("utf8")) data=sk.recv(1024) print(data.decode("utf8"))# import socket## sk=socket.socket()## sk.connect(("127.0.0.1",9904))
#!/usr/bin/env python#-*-coding:utf-8 -*-import selectorsimport socketsel = selectors.DefaultSelector() # IO多路复用的方式有三种,这里根据操作系统拿一个def accept(sock, mask): conn, addr = sock.accept() # Should be ready print('accepted', conn, 'from', addr) conn.setblocking(False) sel.register(conn, selectors.EVENT_READ, read) # 将conn与read函数绑定,一旦conn被触发,与它有关系的就是readdef read(conn, mask): try: data = conn.recv(1000) # Should be ready if not data: raise Exception print('echoing', repr(data), 'to', conn) conn.send(data) # Hope it won't block except Exception as e: print('closing', conn) sel.unregister(conn) conn.close()sock = socket.socket()sock.bind(('localhost', 8090))sock.listen(100)sock.setblocking(False) # 设置非阻塞sel.register(sock, selectors.EVENT_READ, accept) # 将创建的sock对象进行注册,与accept函数绑定print("server.....")while True: events = sel.select() #[sock,..,conn2] for key, mask in events: callback = key.data # callback就是之前绑定的函数名accept(conn变化前) callback(key.fileobj, mask) # key.fileobj就是服务器的sock对象(conn变化前)# import socket# import select# sk=socket.socket()# sk.bind(("127.0.0.1",9904))# sk.listen(5)# while True:# r,w,e=select.select([sk,sk],[],[],5)# r=[sk,]# for i in r:# conn,add=i.accept()# print(conn)# print("hello")## print('>>>>>>')