python 使用epoll非同步處理多個用戶端的串連

來源:互聯網
上載者:User

標籤:python   epoll   select   linux   socket   

伺服器端:

#-*- coding:utf8 -*-import socketimport selectimport osaddress = "0.0.0.0"port = 10001sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)def main():     global address,port,sock     epoll = select.epoll()     #擷取建立好的sock的檔案描述符     fd = sock.fileno()     sock.bind((address,port))     sock_dict = {}     sock_dict[fd] = sock     #對該sock進行註冊     epoll.register(fd,select.EPOLLIN)     sock.listen(5)     while True:         events = epoll.poll(1)         for fileno,event in events:     #擷取到的檔案描述符和sock的相同就說明是一個新的串連             if fileno == fd:                 (client,address) = sock.accept()                 print address                 client.setblocking(0) #將新的串連進行註冊,用來接收訊息                 epoll.register(client.fileno(),select.EPOLLIN)                 sock_dict[client.fileno()] = client            elif event & select.EPOLLIN:                 print "fileno:",fileno                 data = sock_dict[fileno].recv(128)                 if data == '你好':                     print "Data:",data.decode('UTF-8')                     sock_dict[fileno].send("你好")                elif len(data) == 0:                     print "線路%d已下線"%fileno                     epoll.unregister(fileno)                else:                     print "Data:",dataif __name__ == '__main__':    main()

用戶端:

#coding: UTF-8  import socketimport selectaddress = "127.0.0.1"port = 10001sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)def main():    global address,port,sock    sock.connect((address,port))    epoll = select.epoll()    fd = sock.fileno()    #這裡的epoll註冊只是用來非同步接收服務端發過來的訊息    epoll.register(fd,select.EPOLLIN)    while True:        events = epoll.poll(1)        for fileno,event in events:            if fileno == fd:                if event & select.EPOLLIN:                    data = sock.recv(128)                    print data        data = raw_input(">")        if data == 'q':            break        elif data == '':            print "不能發送空訊息"            continue        sock.send(data)    sock.close()main()



python 使用epoll非同步處理多個用戶端的串連

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.