Day8 -- socketserver,

Source: Internet
Author: User

Day8 -- socketserver,

Socketserver category:

1. TCP protocol

Class socketserver. TCPServer (server_address, RequestHandlerClass, bind_and_activate = True)

2. UDP protocol

Class socketserver. UDPServer (server_address, RequestHandlerClass, bind_and_activate = True)

The remaining two uncommon protocols are as follows:

Calss socketserver. UnixStreamServer (server_address, RequestHandlerClass, bind_and_activate = True)

Class socketserver. UnixDatagramServer (server_adddress, RequestHandlerClass, bind_and_activate = True)

The inheritance relationships between protocols are as follows:

To create a service with socketServer:

1. Create a request handler class (request processing class) and reasonably select one of StreamRequestHandler and javasramrequesthandler as the parent class (of course, BaseRequestHandler can also be used as the parent class ), and rewrite its handler () method;

2. instantiate a server class object and pass the service address and the previously created request handler class to it;

3. Call the handle_request () or server_forver () method of the server class object to start processing the request. server_forever () is used to process the connection permanently.

Handle_request () processes only one request and exits after processing one request. server_forever () processes multiple requests.

Every interaction with the client is processed in handle.

SocketServer further encapsulates client functions, such as bind (), listen (), and accept (). These functions are encapsulated in socketserver in a uniform manner and can implement multiple threads, in the case of multi-process and multi-concurrency, the client has not changed. The following is a simple example:

Socketserver:

'''Use socketserver to create a client ''' import socketserverclass MyTCPHandler (socketserver. baseRequestHandler): ''' create a socketserver server acceptor. First, instantiate a class ''' def handle (self): self. data = self. request. recv (1, 1024 ). strip () # receive the message print ("IP: % s, Port: % s link received !!! "% (Self. client_address [0], self. client_address [1]) ''' print that the client port is connected to ''' print (self. data. decode ('utf-8') # print the received message self. request. send (self. data. upper () # Return the received message in uppercase. if _ name _ = "_ main _": HOST, PORT = 'localhost ', 9999 server = socketserver. TCPServer (HOST, PORT), MyTCPHandler) ''' create a connection instance ''' server. serve_forever ()

In the above Code, we created the socketserver instance server. In fact, the principle is the same as that of socket. The difference is that socketserver is an encapsulation of server connection, such as individual bind (), listen (), accept () encapsulation, we only need self. request. recv (length ). strip () can receive data without having to worry too much about underlying issues, making it easy to create a socket.

Client created by socket:

'''Create A socketserver client. The client is exactly the same as the socket Client, but the server side is different. ''' import socketclient = socket. socket () client. connect ("localhost", 9999) while True: mess = input ("Enter the data you want to send >:") client. send (mess. encode ('utf-8') # The client sends data to the server data = client. recv (1024) # print ("received data:", data. decode ('utf-8 '))

The above code is the client created by the socket, which is a simple method of sending and receiving data, where data can be sent continuously. Next, start the server and then start the client for interaction.

Run the following command:

Enter the data you want to send>: dfasfdasd
Received data: DFASFDASD
Enter the data you want to send>: 1
Received data:
Enter the data you want to send>: das
Traceback (most recent call last ):
File "/home/zhuzhu/ et_server/socketserver_client.py", line 8, in <module>
Client. send (mess. encode ('utf-8') # The client sends data to the server
BrokenPipeError: [Errno 32] Broken pipe
From the above, we can see that there is no problem with the first interaction, and an error occurs in the second interaction. Why? Let's take a look at the server side. In the server side, handle () can only receive data once at a time, so an error occurs. Next we will let the server side achieve continuous interaction, modify the server as follows:

'''Use socketserver to create a client ''' import socketserverclass MyTCPHandler (socketserver. baseRequestHandler): ''' create a socketserver server acceptor. First, instantiate a class ''' def handle (self): while True: self. data = self. request. recv (1, 1024 ). strip () # receive the message sent by the client if not self. data: ''' if the received data is null, the server sends NULL data, or the server disconnects ''' print (self. client_address, "the client is disconnected !!! ") Break print (" IP: % s, Port: % s link connected !!! "% (Self. client_address [0], self. client_address [1]) ''' print that the client port is connected to ''' print (self. data. decode ('utf-8') # print the received message self. request. send (self. data. upper () # Return the received message in uppercase. if _ name _ = "_ main _": HOST, PORT = 'localhost ', 9997 server = socketserver. TCPServer (HOST, PORT), MyTCPHandler) ''' create a connection instance ''' server. serve_forever ()

In the code above, the server is modified so that the server can receive data cyclically, so that the client can send and receive data infinitely, but keep in mind that,The client cannot send an empty message to the server.If an empty message is sent to the server, the master will be stuck and the message cannot be delivered. Therefore, you must set the command to send the empty message.

The code above has been modified to implement interaction, but we found a problem. The server can only interact with one client at a time and cannot interact with multiple clients at a time, other clients must wait for the interaction to complete. This is no different from the socket write server and the client. There are two ways to use socketserver to implement multi-concurrency, one is multithreading, as follows:

(1) Multithreading

'''Use socketserver to create a client ''' import socketserverclass MyTCPHandler (socketserver. baseRequestHandler): ''' create a socketserver server acceptor. First, instantiate a class ''' def handle (self): while True: self. data = self. request. recv (1, 1024 ). strip () # receive the message sent by the client if not self. data: ''' if the received data is null, the server sends NULL data, or the server disconnects ''' print (self. client_address, "the client is disconnected !!! ") Break print (" IP: % s, Port: % s link connected !!! "% (Self. client_address [0], self. client_address [1]) ''' print that the client port is connected to ''' print (self. data. decode ('utf-8') # print the received message self. request. send (self. data. upper () # Return the received message in uppercase. if _ name _ = "_ main _": HOST, PORT = 'localhost', 9997Server = socketserver. ThreadingTCPServer (HOST, PORT), MyTCPHandler)'''Create a connection instance ''' server. serve_forever ()

Multithreading is the method of modifying the server connection. socketserver. ThreadingTCPServer can be used as follows:

Server = socketserver. ThreadingTCPServer (HOST, PORT), MyTCPHandler)

After the above modification, we can achieve multi-thread and multi-concurrency. We can start multiple clients for interaction at the same time.

Start a server and multiple clients. The interaction is as follows:

Client 1:
Enter the data you want to send>: This is amazing.
Received data: amazing
Client 2:
Enter the data you want to send>: alex
Received data: ALEX
Client 3:
Enter the data you want to send>: sb
Received data: SB
Client 4:
Enter the data you want to send>: yes
Received data: YES
Server:IP: 127.0.0.1, Port: 54856 link in !!! This amazing IP Address: 127.0.0.1, Port: 54858 link is in !!! AlexIP: 127.0.0.1, Port: 54860 link in !!! SbIP: 127.0.0.1, Port: 54862 link in !!! Yes

As we can see above, we have implemented multi-thread and multi-concurrency interaction, and we can also achieve multi-process interaction.

(2) multi-process

Multi-process and multi-thread are the same. You can modify the interactive commands on the server as follows:

Server = socketserver. ForkingTCPServer (HOST, PORT), MyTCPHandler)

In the preceding example, ForKingTCPServer (IP address, Port Number) is used as an instantiated class to achieve multi-concurrency with multithreading, as shown below:

'''Use socketserver to create a client ''' import socketserverclass MyTCPHandler (socketserver. baseRequestHandler): ''' create a socketserver server acceptor. First, instantiate a class ''' def handle (self): while True: self. data = self. request. recv (1, 1024 ). strip () # receive the message sent by the client if not self. data: ''' if the received data is null, the server sends NULL data, or the server disconnects ''' print (self. client_address, "the client is disconnected !!! ") Break print (" IP: % s, Port: % s link connected !!! "% (Self. client_address [0], self. client_address [1]) ''' print that the client port is connected to ''' print (self. data. decode ('utf-8') # print the received message self. request. send (self. data. upper () # Return the received message in uppercase. if _ name _ = "_ main _": HOST, PORT = 'localhost ', 9997 server = socketserver. forkingTCPServer (HOST, PORT), MyTCPHandler) ''' create a connection instance ''' server. serve_forever ()

The interaction is as follows:

Client 1: Enter the data you want to send>: dfasfdas received data: DFASFDAS client 2: Enter the data you want to send >>: xiaozhuzhu received data: XIAOZHUZHU client 3: Enter the data you want to send>: pangshini Received: PANGSHINI client 4: Enter the data you want to send>: dapagnzhi received data: DAPAGNZHI server: IP: 127.0.0.1, Port: 54876 link in !!! DfasfdasIP: 127.0.0.1, Port: 54878 link in !!! XiaozhuzhuIP: 127.0.0.1, Port: 54880. The link is in !!! PangshiniIP: 127.0.0.1, Port: 54886 link in !!! Dapagnzhi

The above is the multi-process multi-concurrency interaction, which is consistent with the multi-thread interaction result. The difference is that,ForKingTCPServer () multi-process reports an error in WindowsWindows multi-process and Linux multi-process have different principles. There is no problem in Linux, and an error will be reported in Windows.

Basic socketserver code:

 

import socketserverclass 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()

 

Summary:

(1) The socketserver and socket are the same in order to achieve interaction between the client and the server;

(2) socketserver can achieve multi-concurrency, while socket can only perform one-to-one interaction;

(3) socketserver. TCPServer implements one-to-one interaction with socket, socketserver. threadingTCPServer is a multi-thread multi-concurrency, socketserver. forkingTCPServer is used to implement multi-process multi-concurrency data interaction. It interacts with each other under the TCP protocol, and UDP is also commonly used.

(4)The client cannot send empty messages, and the server cannot receive empty messages.;

(5) If the message received by the server is empty, it indicates that the client has exited. Otherwise, the client will be blocked if it is empty;

(6) socketserver is the encapsulation of bind, listen, accept () in socket.

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.