天天看點

非阻塞IO模闆

服務端

from socke import *

server = socket(AF_INET, SOCK_STREAM)
server.bind(('127.0.0.1',8083))
server.listen(5)
server.setblocking(False)     #1
print('starting...')


rlist=[]   #連結套接字加到rlist裡 ["連結類型","協定","ip,port"]
wlist=[]
while True:

    try:
        conn, addr = server.accept()
        rlist.append(conn)
        print(rlist)
    except BlockingIOError:  # 檢測BlockingIOError
        # print('幹其他的活')

        #收消息
        del_rlist = []
        for conn in rlist:  #周遊套接字,有消息過來。就繼續下一步,
        # 沒消息過來就交conn添加到del_rlist,再去通過del_list清單remove掉rlist裡的conn
            try:
                data=conn.recv(1024)
                if not data:
                    del_rlist.append(conn)
                    continue
                wlist.append((conn,data.upper()))
            except BlockingIOError:  # 檢測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 conn in del_rlist:
            rlist.remove(conn)


server.close()      

用戶端

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()