【Python】非阻塞IO

#  特点:不断对服务进行询问,以实现非IO阻塞模型
# 缺点: 1.不断询问导致CPU占用高
# 2.询问的间隔时间中,客户端发送的请求无法响应
# 不推荐使用!


from socket import *


class Server(object):
def __init__(self, ip_bind=('127.0.0.1', 8080)):
self.head_buffer = 1024
self.coding = 'utf-8'
self.server = socket(AF_INET, SOCK_STREAM)
self.server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
self.server.bind(ip_bind)
self.server.listen(50)
self.server.setblocking(False) # 非阻塞模型IO
self.connect_list = []
self.recv_list = []
self.send_list = []
self.disconnect_list = []

def run(self):
while 1:
self.connect()
self.recv()
self.work()
self.send()
self.end()

def connect(self):
try:
conn, address_link = self.server.accept() # 没链接会弹出异常
self.connect_list.append(conn)
except BlockingIOError:
return

def recv(self):
for conn in self.connect_list:
try:
msg = conn.recv(self.head_buffer)
if not msg:
self.disconnect_list.append(conn)
return
data = msg.decode(self.coding)
self.recv_list.append((conn, data))
except BlockingIOError:
continue
except Exception:
self.disconnect_list.append(conn)

def work(self):
del_list = []
for conn, msg in self.recv_list:
self.send_list.append((conn, msg.upper()))
del_list.append((conn, msg))
for msg in del_list:
self.recv_list.remove(msg)

def send(self):
del_list = []
print(self.send_list)
for conn, data in self.send_list:
try:
conn.send(data.encode(self.coding))
del_list.append((conn,data))
except BlockingIOError:
continue
for msg in del_list:
self.send_list.remove(msg)

def end(self):
del_list = []
for conn in self.disconnect_list:
self.connect_list.remove(conn)
conn.close()
del_list.append(conn)

for conn in del_list:
self.recv_list.remove(conn)


if __name__ == '__main__':
s = Server()
s.run()
posted @ 2018-08-26 18:08  caya  阅读(346)  评论(0编辑  收藏  举报