python---socket and socketserver

1. The socket side socket.getaddrinfo(host, port, family=0, type=0, proto=0, flags=0) #Get the address of the peer host to connect to sk.bind(address)

  Bind the socket to the address. The format of the address address depends on the address family. Under AF_INET, the address is represented as a tuple (host, port).

sk.listen(backlog) Start listening for incoming connections. The backlog specifies the maximum number of connections that can be suspended before rejecting the connection. The backlog is equal to 5, indicating that the kernel has received a connection request, but the server has not called accept for processing. The maximum number of connections is 5. This value cannot be infinite, because the connection queue needs to be maintained in the kernel. sk.setblocking(bool) Whether to block (default True), if set to False, then an error will be reported once there is no data during accept and recv.
sk.accept() Accept the connection and return (conn, address), where conn is the new socket object that can be used to receive and send data. address is the address of the connecting client. Receive connections from TCP clients (blocking) and wait for a connection to arrive sk.connect(address) Connect to the socket at address. Generally, the format of address is a tuple (hostname, port). If the connection fails, socket.error is returned. sk.connect_ex(address) Same as above, but there will be a return value, 0 is returned when the connection is successful, and the code is returned when the connection fails, for example: 10061 sk.close() close the socket sk.recv(bufsize[,flag]) Accept socket data. The data is returned as a string, and bufsize specifies the maximum amount that can be received. flag provides additional information about the message and can usually be ignored. sk.recvfrom(bufsize[.flag]) Similar to recv(), but the return value is (data, address). where data is a string containing the received data and address is the socket address from which the data was sent. sk.send(string[,flag]) Send the data in string to the connected socket. The return value is the number of bytes to send, which may be less than the byte size of the string. That is: all the specified contents may not be sent. sk.sendall(string[,flag]) Sends the data in string to the connected socket, but tries to send all the data before returning. Returns None on success, throws an exception on failure. Internally, send everything out by recursively calling send. sk.sendto(string[,flag],address) Send data to the socket, address is a tuple of the form (ipaddr, port) specifying the remote address. The return value is the number of bytes sent. This function is mainly used for the UDP protocol. sk.settimeout(timeout) Sets the timeout period for socket operations, timeout is a floating point number in seconds. A value of None means no timeout period. In general, timeouts should be set when the socket is just created,
because they may be used for connection operations (eg client connection waits up to 5s) sk.getpeername() Returns the remote address of the connected socket. The return value is usually a tuple (ipaddr, port). sk.getsockname() Returns the socket's own address. Usually a tuple (ipaddr, port) sk.fileno () file descriptor of the socket socket.sendfile(file, offset=0, count=None) Send file

2. Socketserver:
  Socketserver contains two classes, one is server class and the other is request handle class. The former provides many methods: like binding, listening, running... (that is, the process of establishing a connection) The latter focuses on how to process the data sent by the user (that is, transaction logic).
  In general, all services first establish a connection, that is, an instance of a service class, and then start processing user requests, that is, create an instance of a request processing class.
  
To support the asynchronous model, multiple inheritance can be used to make the server class inherit the ForkingMixIn or ThreadingMixIn mix-in classes.
  ForkingMixIn utilizes multiple processes (forking) to achieve asynchrony. ThreadingMixIn uses multiple threads to achieve asynchrony.

  Request handler class:

  To implement a service, you must also derive a handler class request handling class and override the handle() method of the parent class. The handle method is used specifically to handle requests. This module handles requests through a combination of service classes and request handling classes.

  The request processing classes provided by the SocketServer module are BaseRequestHandler, and its derived classes StreamRequestHandler and DatagramRequestHandler. From the name, it can be seen that one handles stream sockets and one handles datagram sockets.

  Steps to create a service with socketserver:

  1 Create a request handler class (request processing class), reasonably select one of StreamRequestHandler and DatagramRequestHandler as the parent class (of course, you can also use BaseRequestHandler as the parent class), and rewrite its handle() method.

  2 Instantiate a server class object and pass it the address of the service and the previously created request handler class.

  3 Call the handle_request() or serve_forever() method of the server class object to start processing the request.

  Service-Terminal:
import socketserver
 
class MyTCPHandler (socketserver.BaseRequestHandler):
    """
    The request handler class for our server.
 
    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """
 
    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print("{} wrote:".format(self.client_address[0]))
        print(self.data)
        # just send back the same data, but upper-cased
        self.request.sendall(self.data.upper())
 
if __name__ == "__main__":
    HOST, PORT = "localhost", 9999
 
    # Create the server, binding to localhost on port 9999
    server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
 
    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324997702&siteId=291194637