Python-based socket server for select

Source: Internet
Author: User
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.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.