非阻塞IO
Posted fmgao-technology
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了非阻塞IO相关的知识,希望对你有一定的参考价值。
server------------------------
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2018/6/19 9:33
# @File : server1.py
from socket import *
server = socket(AF_INET, SOCK_STREAM)
server.bind((‘127.0.0.1‘, 8080))
server.listen(5)
server.setblocking(False) # 使得下面所有IO都是非阻塞
print(‘starting...........‘)
rlist = []
wlist = []
while True:
try:
conn, addr = server.accept() # 建立连接
rlist.append(conn)
print(rlist)
except BlockingIOError:
# 收消息
del_rlist = []
for conn in rlist:
try:
data = conn.recv(1024)
if not data:
del_rlist.append(conn)
continue
# con.send(data.upper()) # 这种方式在数据量大的时候也会有问题
wlist.append((conn, data.upper()))
except BlockingIOError:
continue
except Exception:
conn.close()
del_rlist.append(conn)
# 发消息
del_wlist = []
for item in wlist:
try:
conn = item[0]
data = item[1]
conn.send[data]
del_wlist.append(item)
except BlockingIOError:
pass
for item in del_wlist:
wlist.remove(item)
for del_con in del_rlist:
rlist.remove(del_con)
server.close()
# 缺点,1、无法及时响应客户端2、cpu无用功一直运行(死循环)
client---------------------
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2018/6/19 9:33
# @File : client1.py
# 右键运行一次就是一个进程
from socket import *
client = socket(AF_INET, SOCK_STREAM)
client.connect((‘127.0.0.1‘, 8080))
while True:
msg = input(‘>>>:‘).strip()
if not msg:continue
client.send(msg.encode(‘utf-8‘))
data = client.recv(1024)
print(data.decode(‘utf-8‘))
client.close()
以上是关于非阻塞IO的主要内容,如果未能解决你的问题,请参考以下文章