Home >Backend Development >Python Tutorial >Implementation of single-threaded multitasking in Python

Implementation of single-threaded multitasking in Python

巴扎黑
巴扎黑Original
2017-08-08 14:41:291600browse

This article mainly introduces the relevant information of python to implement single-threaded multi-tasking non-blocking TCP server in detail. It has certain reference value. Interested friends can refer to it.

The examples of this article are Everyone has shared the specific code for implementing single-threaded multi-tasking non-blocking TCP server in Python for your reference. The specific content is as follows


# coding:utf-8
from socket import *

# 1.创建服务器socket
sock = socket(AF_INET, SOCK_STREAM)

# 2.绑定主机和端口
addr = ('', 7788) #
sock.bind(addr)

# 3. 设置最大监听数目,并发
sock.listen(10)

# 4. 设置成非阻塞
sock.setblocking(False)
# 保存客户端socket
clientAddrList = []
# print(sock.)

while 1:
  try:
    clientSocket, clientAddr = sock.accept()
  except:
    pass
  else:
    print("一个新客户端到来:%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 已经下线" % str(clientAddr))

The above is the detailed content of Implementation of single-threaded multitasking in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn