server:
import select import socket sk = socket.socket() sk.bind(('127.0.0.1',8000)) sk.setblocking(False) sk.listen() read_lst = [sk] while True: # [sk,conn] r_lst,w_lst,x_lst = select.select(read_lst,[],[]) for i in r_lst: if i is sk: conn,addr = i.accept() read_lst.append(conn) else: ret = i.recv(1024) if ret == b'': i.close() read_lst.remove(i) continue print(ret) i.send(b'goodbye!')
client:
import time import socket import threading def func(): sk = socket.socket() sk.connect(('127.0.0.1',8000)) sk.send(b'hello') time.sleep(3) print(sk.recv(1024)) sk.close() for i in range(20): threading.Thread(target=func).start()
IO multiplexing of three mechanisms:
select :windows linux
poll;linux
eploo:linux
Link: https: //www.cnblogs.com/Eva-J/articles/8324837.html
import selectors from socket import * def accept(sk,mask): conn,addr=sk.accept() sel.register(conn,selectors.EVENT_READ,read) def read(conn,mask): try: data=conn.recv(1024) if not data: print('closing',conn) sel.unregister(conn) conn.close() return conn.send(data.upper()+b'_SB') exceptException: Print ( ' the closing ' , Conn) sel.unregister (Conn) conn.Close () SK = Socket () sk.setsockopt (SOL_SOCKET, the SO_REUSEADDR, . 1 ) sk.bind (( ' 127.0.0.1 ' , 8088 )) sk.listen ( 5 ) sk.setblocking (False) # set socket interface for non-blocking SEL = selectors.DefaultSelector () # to select a suitable mechanism for my IO multiplexed sel.register (sk, selectors.EVENT_READ, the Accept) # equivalent net select reading list append a sk object, and a callback function to bind the Accept # it means if someone requests a connection sk, calls the method accrpt the while True: Events = sel.select () # detect all sk, conn, wait data for the completion stage for sel_obj, mask in Events: # [Conn] the callback = sel_obj.data # the callback = Read the callback (sel_obj.fileobj, mask) # the Read (conn, 1)