Python異步通信模塊asyncore


Python異步通信模塊asyncore

介紹

Python的asyncore模塊提供了以異步的方式寫入套接字服務的client和server的基礎結構。

模塊主要包含:

  • asyncore.loop(…) - 用於循環監聽網絡事件。loop()函數負責檢測一個字典。字典中保存dispatcher的實例。

  • asyncore.dispatcher類 - 一個底層套接字對象的簡單封裝。這個類有少數由異步循環調用的,用來事件處理的函數。

    • dispatcher類中的writable()和readable()在檢測到一個socket能夠寫入或者數據到達的時候被調用,並返回一個bool值,決定是否調用handle_read或者handle_write。

  • asyncore.dispatcher_with_send類 - 一個 dispatcher的子類,加入了簡單的緩沖輸出能力。對簡單的client非常實用。

樣例

以下看一個簡單的樣例

import time
import asyncore
import socket
import threading


class EchoHandler(asyncore.dispatcher_with_send):

    def handle_read(self):
        data = self.recv(1024)
        if data:
            self.send(data)

class EchoServer(asyncore.dispatcher):

    def __init__(self, host, port):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.set_reuse_addr()
        self.bind((host, port))
        self.listen(5)

    def handle_accept(self):
        conn, addr = self.accept()
        print 'Incoming connection from %s' % repr(addr)
        self.handler = EchoHandler(conn)

class EchoClient(asyncore.dispatcher):

    def __init__(self, host, port):
        asyncore.dispatcher.__init__(self)
        self.messages = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect((host, port))

    def handle_connect(self):
        pass

    def handle_close(self):
        self.close()

    def handle_read(self):
        print self.recv(1024)

    def writable(self):
        return (len(self.messages) > 0)

    def handle_write(self):
        if len(self.messages) > 0: 
            self.send(self.messages.pop(0))

class EchoServerThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        server = EchoServer('localhost', 9999)
        asyncore.loop()

class EchoClientThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        client = EchoClient('localhost', 9999)
        asyncore.loop()

EchoServerThread().start()
time.sleep(2)
EchoClientThread().start()
  • EchoServer - 響應server端程序。負責監聽一個端口,並響應client發送的消息然后原樣返回給client。

    當中handle_accept()方法定義當一個連接到來的時候要執行的操作,這里指定了使用一個Handler來出來發送來的數據。

  • EchoHandler - server端數據響應類,接收數據並把數據原樣發回。

  • EchoClient - 響應服務client程序,負責連接響應server。當中

    • messages - 定義了一個要發送的消息列表,每次發送一個消息。知道列表為空為止。

    • handle_read() - 處理接收到的數據。這里把收到的數據打印的終端上。

    • writable() - 推斷是否有數據能夠向server端發送。

    • handle_write() - 當writable()函數返回True時,寫入數據。

  • EchoServerThread - 用來啟動server端程序的線程。

  • EchoClientThread - 用來啟動client端程序的線程。

測試

執行上面的測試代碼。能夠看到server和client建立了連接后,響應了client發送來的10個數字。然后關閉了連接。

Incoming connection from ('127.0.0.1', 51424)
1
2
3
4
5
6
7
8
9
10

轉載請以鏈接形式標明本文地址
本文地址:http://blog.csdn.net/kongxx/article/details/51158775


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM