python implements single threaded multitask non blocking TCP server
- 2020-06-03 07:15:10
- OfStack
This article shares the specific code of python's implementation of single-threaded multitask non-blocking TCP server for your reference. The specific content is as follows
# coding:utf-8
from socket import *
# 1. Create server socket
sock = socket(AF_INET, SOCK_STREAM)
# 2. Bind host and port
addr = ('', 7788) #
sock.bind(addr)
# 3. Sets the maximum number of listens and concurrency
sock.listen(10)
# 4. Set to non-blocking
sock.setblocking(False)
# Save client socket
clientAddrList = []
# print(sock.)
while 1:
try:
clientSocket, clientAddr = sock.accept()
except:
pass
else:
print("1 A new client arrives: %s" % str(clientAddr))
clientSocket.setblocking(False)
clientAddrList.append((clientSocket, clientAddr))
for clientSocket, clientAddr in clientAddrList:
try:
recvData = clientSocket.recv(1024)
except:
pass
else:
if len(recvData) > 0:
print("%s:%s" % (str(clientAddr), recvData))
else:
clientSocket.close()
clientAddrList.remove((clientSocket, clientAddr))
print("%s Has been rolled off the production line " % str(clientAddr))