python实现单线程多任务非阻塞TCP服务端
本文实例为大家分享了python实现单线程多任务非阻塞TCP服务端的具体代码,供大家参考,具体内容如下
# 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))
相关推荐
txj 2020-06-02
一叶梧桐 2020-10-14
lzzyok 2020-10-10
houjinkai 2020-06-03
简单的快乐 2020-05-09
zkwgpp 2020-05-04
CloudXli 2020-04-20
Noseparte 2020-03-26
x青年欢乐多 2020-03-02
digwtx 2020-09-14
efeve 2020-09-14
poplpsure 2020-08-17
ITxiaobaibai 2020-07-26
libowenhit 2020-07-23
luckykapok 2020-07-06
hongsheyoumo 2020-06-27
jannal 2020-06-21