Write a simple Web server that returns a line of text to each Web browser that connects to the server.
The script core calls Select.epoll () during the initialization of the Web server, registering the server's file descriptor, and has reached the purpose of event notification.
1 #!/usr/bin/env python2 #-*-coding:utf-8-*-3 4 ImportSocket5 ImportSelect6 ImportArgparse7 8Server_host ='localhost'9 TenEOL1 = b'\ n' OneEOL2 = b'\n\r\n' AServer_response = b"""http/1.1 Ok\r\ndate:mon, 1 Apr 01:01:01 Gmt\r\ncontent-type:text/plain\r\ncontent-length:25\r\n\r\nhello From Epoll server!""" - - classEpollserver (object): the """a socket server using Epoll""" - def __init__(Self, host=server_host, port=0): -Self.sock =Socket.socket (socket.af_inet, socket. SOCK_STREAM) - #Creating Sockets +Self.sock.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, 1) - #set the current socket option to be reusable +Self.sock.bind ((host, Port))#binding ASelf.sock.listen (1)#Monitor atSelf.sock.setblocking (0)#set socket mode to non-blocking -Self.sock.setsockopt (socket. IPPROTO_TCP, Socket. Tcp_nodelay, 1) - #The socket blocking mode automatically turns on the Nagle algorithm. The SET socket option is turned off. The Nagle algorithm is used to automatically connect a certain number of messages within a buffer. - Print "Started epoll Server" -Self.epoll = Select.epoll ()#Create a Epoll object - Self.epoll.register (Self.sock.fileno (), select. Epollin) in #register interest for the socket's Read event - #Epollin indicates that the corresponding file descriptor can be read, including a graceful shutdown of the peer socket to #Fileno () returns an integer file descriptor for the socket + - defRun (self): the """executes Epoll server Operation""" * Try: $Connections = {}#mapping the Connection object to the socket objectPanax NotoginsengRequests = {} -responses = {} the whileTrue: +Events = Self.epoll.poll (1) A #queries whether the Epoll object can occur for any interest event. 1 Wait a second the forFileno, EventinchEvents#Traversing Events + #If the event occurs on the server - ifFileno = =Self.sock.fileno (): $Connection, address = self.sock.accept ()#receiving client sockets and addresses $Connection.setblocking (0)#set non-blocking mode - Self.epoll.register (Connection.fileno (), select. Epollin) - #register interest for the new socket's Read event theConnections[connection.fileno ()] = connection#Add to Connections -Requests[connection.fileno ()] = b"'WuyiResponses[connection.fileno ()] = Server_response#What to send the - #If a read event occurs on the client, read the new data sent from the client Wu elifEvent &Select. Epollin: -Requests[fileno] + = CONNECTIONS[FILENO].RECV (1024) About ifEOL1inchRequests[fileno]orEOL2inchRequests[fileno]: $ self.epoll.modify (Fileno, select. Epollout) - #Unregisters the interest of the Read event, registering the interest for the write event - Print('-'*40 +'\ n'+ Requests[fileno].decode () [:-2]) - #output a complete request to remove the last \ r \ n A + #If a write event occurs on the client, it is possible to accept new data from the client the elifEvent &Select. Epollout: - #epollout indicates that the corresponding file descriptor can be written $Byteswritten =connections[fileno].send (Responses[fileno]) theResponses[fileno] =Responses[fileno][byteswritten:] the ifLen (Responses[fileno]) = = 0:#if not responding theSelf.epoll.modify (Fileno, 0)#Disable Interest the Connections[fileno].shutdown (socket. SHUT_RDWR) - #close the corresponding socket connection in the #If an Abort event occurs on the client the elifEvent &Select. Epollhup: About #epollhup indicates that the corresponding file descriptor is hung off theSelf.epoll.unregister (Fileno)#Logoff Client Interest theConnections[fileno].close ()#Close the socket connection the delConnections[fileno]#Delete Mappings + finally: -Self.epoll.unregister (Self.sock.fileno ())#Unregister server Interest theSelf.epoll.close ()#shutting down the server EpollBayiSelf.sock.close ()#shutting down the server socket the the if __name__=='__main__': -Parser = Argparse. Argumentparser (description='Socket Server Example with Epoll') -Parser.add_argument ('--port', action="Store", dest="Port", Type=int, required=True) theGiven_args =Parser.parse_args () thePort =Given_args.port theServer = Epollserver (Host=server_host, port=Port) theServer.run ()
References: "Python Network programming Cookbook"
Http://scotdoyle.com/python-epoll-howto.html#source-code
Epoll writing a Web server