The example in this article describes Python's socket server based on select. Share to everyone for your reference, as follows:
Using method of Select.select in Asyncore module
Import Socketimport Tracebackimport selectEOL1 = B ' \ n ' EOL2 = B ' \n\r\n ' Socketmap = {}r,w,e = [],[],[]response = B ' HTTP/1. 0 Ok\r\ndate:mon, 1 Jan 1996 01:01:01 gmt\r\n ' response + = B ' content-type:text/plain\r\ncontent-length:13\r\n\r\n ' re Sponse + = B ' Hello, world! ' ServerSocket = Socket.socket (socket.af_inet, socket. SOCK_STREAM) serversocket.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, 1) serversocket.bind ((' 0.0.0.0 ', 23456)) Serversocket.listen (1) #serversocket. setblocking (0) Listening _fileno = Serversocket.fileno () Socketmap[listening_fileno] = Serversocketprint ' Listening_fileno ', listening_ Filenotry:while true:r,w,e = [],[],[] for FD in Socketmap:r.append (FD) w.append (FD) e.append (FD) R,w,e = Select.select (r,w,e,1) for FD in r:request = B ' Isocket = socketmap[fd] if fd = = Listening_ Fileno:print ' accepting ' clientsock,clientaddr = isocket.accept () #clientsock. setblocking (0) Cli_fileno = Clientsock.fileno() r.append (Cli_fileno) w.append (Cli_fileno) e.append (Cli_fileno) Socketmap[cli_fileno] = Clie Ntsock Else:print ' reading ' while EOL1 not on request and EOL2 not in request:request + = ISO CKET.RECV (1024x768) print (Request.decode ()) for FD in W:print ' writing ' osocket = socketmap[fd] Osoc Ket.send (response) for FD in e:esocket = socketmap[fd] print ' socket close ', FD esocket.close () del SOCKETMAP[FD] print "No data coming" except Exception,e:print Traceback.print_exc () serversocket.close ()
More readers interested in Python related content can view the topic: Python string manipulation tips Summary, Python Introductory and Advanced classic tutorials, and Python file and directory Operations Tips Summary
I hope this article is helpful for Python program design.