Python programming scoketServer implements multi-thread synchronization of instance code, pythonscoketserver

Source: Internet
Author: User

Python programming scoketServer implements multi-thread synchronization of instance code, pythonscoketserver

This article focuses on the Python programming scoketServer to implement multi-thread synchronization. The details are as follows.

During development, only one common data can be used at the same time for different clients.

Although it is very convenient to write simple network programs in Python, it is better to use a ready-made framework for complicated network programs. In this way, you can concentrate on the transaction logic, rather than the socket details. The SocketServer module simplifies the preparation of network service programs. The SocketServer module is also the basis of many server frameworks in the Python standard library.

Network Service class:

SocketServer provides four basic services:

TCPServer for TCP socket stream
UDPServer for UDP datagram socket
UnixStreamServer and unixw.ramserver are not commonly used for UNIX domain sockets.

First, it is clear that in scoketServer, every time a client is successfully connected, a thread is created for each client.

In order to allow synchronous execution between these threads, my practice is: create another thread class, which does what my project needs to do ,, when a client wants to use this thread, it locks the current thread and releases the lock after running.

Please advise

For detailed steps, see notes:

# Coding = gbk _ author _ = 'kaikaiai' import Queueimport threadingimport timeimport SocketServer # global thread lock threadLock = threading. lock () # global data Queue data = Queue. queue () # Working thread class, class testThead (threading. thread): global data def _ init _ (self): threading. thread. _ init _ (self) def begin_test (self): self. start () def run (self): global threadLock. acquire () # retrieve the connection and data from the queue if data. qsize ()> 0: this_receive = data. g Et () else: print "data size is empty! "Return # parse the data and obtain the connection and data # Use the conn this_conn = this_receive.keys () [0] this_data = this_receive [this_conn] # Release the threadLock lock. release () def send_msg (self, conn, msg): try: conn. sendall (msg) failed t Exception as e: print "send" + str (msg) + "fail !!!!!!!!!!!!!! "Def recv_msg (self, conn): try: recv_msg = conn. recv (2048) return recv_msg failed t Exception as e: print "recv msg fail !!!!!!!!!! "Return None # each client generates a thread. All threads call the same test thread. If the test thread is locked, wait. Class MyServer (SocketServer. baseRequestHandler): def send_msg (self, conn, msg): try: conn. sendall (msg) failed t Exception as e: print "send" + str (msg) + "fail !!!!!!!!!!!!!! "Def recv_msg (self, conn): try: recv_msg = conn. recv (2048) return recv_msg failed t Exception as e: print "recv msg fail !!!!!!!!!! "Def handle (self): global data # Get connection conn = self. request print" client connect! "# Cyclically accept client data while True: # accept the receive_data parameter sent by the client. recv_msg (conn) print receive_data # if the parameter is null, an error is returned indicating the end of the loop if not receive_data: print "can not get data form client! "Break print" data size put before: "+ str (data. qsize () # adding connections and data to a queue and placing them in a connection ensures that the connection is directly used in another thread to send or receive data to the corresponding client. At the same time, ensure that the data exactly corresponds to the client. put ({conn: receive_data}) print "data size put aftter:" + str (data. qsize () # initialize the test thread testThead_this = testThead () # start the test thread testThead_this.begin_test () # testThead_this.start () # Wait until the test thread execution ends testThead_this.join () print "this test end" if _ name _ = "_ main _": try: server = SocketServer. threadingTCPServer ('2017. 168.100.100 ', 56780), MyServer) server. timeout = 100 print "Server r Un success !!!! "Server. serve_forever () failed t Exception as e: print" Server run failed !!!! \ N error: "+ str (e)

Summary

The above is all the content of the Python programming scoketServer to implement multi-threaded synchronization of instance code. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!

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.