IO_多路複用_select_epool模式

select_socket_server簡單實例
import select,socket,queue

server=socket.socket()

server.bind(('localhost',9000))
server.listen(1000)

server.setblocking(False)#設置非阻塞模式

inputs=[server,]
#inputs=[server,conn] #[conn,]
#inputs=[server,conn,conn2] #[conn2,]
outputs=[]
while True:
    readable,writeable,exceptional=select.select(inputs,outputs,inputs)#select監測server連接  返回三個數據
    print(readable,writeable,exceptional)
    for r in readable:
        if r is server:#代表來了一個新連接 下一次select
            conn,addr=server.accept()
            print("來了一個新連接:",addr)
            inputs.append(conn)#是因爲這個新建立的連接還沒發數據過來,現在就接收的話程序就報錯了,
            #所以要想實現這個客戶端發數據來時server端能知道,就需要讓select在監測這個conn
        else:#如果不是新連接,是之前那個conn 就接收數據 下一次select
            data=r.recv(1024)
            print("收到數據:",data)
            data1=(str(data.decode("utf-8")).upper()).encode()
            r.send(data1)
            print("send done...")

 

 

有隊列的select_socket_server實例
import select,socket,queue

server=socket.socket()

server.bind(('localhost',9000))
server.listen(1000)

server.setblocking(False)#設置非阻塞模式

msg_dic={}

inputs=[server,]
#inputs=[server,conn] #[conn,]
#inputs=[server,conn,conn2] #[conn2,]
outputs=[] #r
#outputs=[r1,]
while True:
    readable,writeable,exceptional=select.select(inputs,outputs,inputs)#select監測server連接  返回三個數據
    print(readable,writeable,exceptional) #outputs 放啥下一次就出啥 下一次循環的時候就返回了
    for r in readable:
        if r is server:#代表來了一個新連接 下一次select
            conn,addr=server.accept()
            print("來了一個新連接:",addr)
            inputs.append(conn)#是因爲這個新建立的連接還沒發數據過來,現在就接收的話程序就報錯了,
            #所以要想實現這個客戶端發數據來時server端能知道,就需要讓select在監測這個conn
            msg_dic[conn]=queue.Queue()#初始化一個隊列,後面存要返回給這個客戶端的數據

        else:#如果不是新連接,是之前那個conn 就接收數據 下一次select
            data=r.recv(1024)
            print("收到數據:",data)
            msg_dic[r].put(data) #往隊列裏面扔數據 等於字典裏添加values

            outputs.append(r) #放入返回的連接隊列裏
            #r.send(data)
            #print("send done...")

    for w in writeable:#要返回給客戶端的連接列表
        data_to_client=msg_dic[w].get() #返回給這個客戶端的數據 取隊列裏面的數據 相當於取字典裏面的values
        w.send(data_to_client)#返回給客戶端的源數據

        outputs.remove(w)#確保下次循環的時候writeable,不返回已經處理完的連接

    for e in exceptional:#連接已經斷開,異常處理
        if e in outputs:
            outputs.remove(e)#清理已經斷開的連接

        inputs.remove(e)#清理已經斷開的連接

        del msg_dic[e]#清理已經斷開的連接

 

 

支持大併發的selectors模塊
import selectors
import socket

sel = selectors.DefaultSelector()


def accept(sock, mask):#相當於server.accept()
    conn, addr = sock.accept()  # Should be ready
    print('accepted', conn, 'from', addr)
    conn.setblocking(False)
    sel.register(conn, selectors.EVENT_READ, read)#新連接註冊read回調函數


def read(conn, mask):#操作
    data = conn.recv(1024)  # Should be ready
    if data:
        print('echoing', repr(data), 'to', conn,mask)
        conn.send(data)  # Hope it won't block
    else:
        print('closing', conn)
        sel.unregister(conn)
        conn.close()


sock = socket.socket()
sock.bind(('localhost', 10000))
sock.listen(1000)
sock.setblocking(False)
sel.register(sock, selectors.EVENT_READ, accept)

while True:
    events = sel.select() #看系統支持 select或 epool 默認阻塞 有活動連接就返回活動的連接列表
    for key, mask in events:
        callback = key.data #accept
        callback(key.fileobj, mask) #key.fileobj=文件句柄

 


多路連接socket_client
#_*_coding:utf-8_*_
__author__ = 'Alex Li'


import socket
import sys

messages = [ b'This is the message. ',
             b'It will be sent ',
             b'in parts.',
             ]
server_address = ('localhost',10000)

# Create a TCP/IP socket
socks = [ socket.socket(socket.AF_INET, socket.SOCK_STREAM) for i in range(100)
          ]

# Connect the socket to the port where the server is listening
print('connecting to %s port %s' % server_address)
for s in socks:
    s.connect(server_address)

for message in messages:

    # Send messages on both sockets
    for s in socks:
        print('%s: sending "%s"' % (s.getsockname(), message) )
        s.send(message)

    # Read responses on both sockets
    for s in socks:
        data = s.recv(1024)
        print( '%s: received "%s"' % (s.getsockname(), data) )
        if not data:
            print( 'closing socket', s.getsockname() )

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章