码迷,mamicode.com
首页 > 其他好文 > 详细

非阻塞IO

时间:2018-06-20 16:37:10      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:continue   enc   als   connect   exception   数据   sock   usr   serve   

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

标签:continue   enc   als   connect   exception   数据   sock   usr   serve   

原文地址:https://www.cnblogs.com/fmgao-technology/p/9204249.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!