Python socket multithreading and multi-process

Source: Internet
Author: User

In the socket, if created directly, only one user's request can be accepted
Need to implement handle method in Socketserver, can implement multi-process concurrent access

The Socketserver internally uses IO multiplexing and "multithreading" and "multi-process" to enable the socket service side to process multiple client requests concurrently. That is, when each client requests a connection to the server, the socket server is creating a "thread" or "process" dedicated to all requests from the current client.

1. Create a inherit from Socketserver. Baserequesthandler class, a method named handle must be defined in the class
2. Start Threadingtcpserver

import socketserverclass MyServer(socketserver.BaseRequestHandler):    def handle(self):        conn = self.request        conn.sendall("我是一个多线程".encode())        Flag = True        while Flag:            data = conn.recv(1024)            if data.decode() == "exit":                Flag = False            conn.sendall(data)if __name__ == "__main__":    server = socketserver.ThreadingTCPServer((‘127.0.0.1‘,8009),MyServer)    server.serve_forever()
客户端直接使用原来的客户端代码即可。

Threadingtcpserver
The Soket server implemented by Threadingtcpserver creates a "thread" for each client that is used to interact with the client.

Python socket multithreading and multi-process

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: [email protected] 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.