Python implements single-thread multi-task non-blocking TCP server, python single-Thread
The examples in this article share the code for implementing Single-thread multi-task non-blocking TCP server in python for your reference. The details are as follows:
# Coding: utf-8from socket import * #1. create server socketsock = socket (AF_INET, SOCK_STREAM) #2. bind host and port addr = ('', 7788) # sock. bind (addr) #3. set the maximum number of listeners and concurrent sock. listen (10) #4. set to non-blocking sock. setblocking (False) # Save the client socketclientAddrList = [] # print (sock .) while 1: try: clientSocket, clientAddr = sock. accept () handle T: pass else: print ("arrival of a new client: % s" % str (clientAddr) clientSocket. setblocking (False) clientAddrList. append (clientSocket, clientAddr) for clientSocket, clientAddr in clientAddrList: try: recvData = clientSocket. recv (1024) failed T: pass else: if len (recvData)> 0: print ("% s: % s" % (str (clientAddr), recvData) else: clientSocket. close () clientAddrList. remove (clientSocket, clientAddr) print ("% s offline" % str (clientAddr ))
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.