Python異步通信模塊asyncore解讀
Python異步通信模塊asyncore
Python的asyncore模塊提供了以異步的方式寫入套接字服務的客戶端和服務器的基礎結(jié)構(gòu)。
模塊主要包括
asyncore.loop(…)
- 用于循環(huán)監(jiān)聽網(wǎng)絡事件。loop()函數(shù)負責檢測一個字典,字典中保存dispatcher的實例。asyncore.dispatcher
類 - 一個底層套接字對象的簡單封裝。這個類有少數(shù)由異步循環(huán)調(diào)用的,用來事件處理的函數(shù)。dispatcher
類中的writable()和readable()在檢測到一個socket可以寫入或者數(shù)據(jù)到達的時候被調(diào)用,并返回一個bool值,決定是否調(diào)用handle_read或者handle_write。asyncore.dispatcher_with_send
類 - 一個 dispatcher的子類,添加了簡單的緩沖輸出能力,對簡單的客戶端很有用。
例子
下面看一個簡單的例子
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 - 響應服務器端程序,負責監(jiān)聽一個端口,并響應客戶端發(fā)送的消息然后原樣返回給客戶端。
其中handle_accept()方法定義當一個連接到來的時候要執(zhí)行的操作,這里指定了使用一個Handler來出來發(fā)送來的數(shù)據(jù)。
EchoHandler - 服務器端數(shù)據(jù)響應類,接收數(shù)據(jù)并把數(shù)據(jù)原樣發(fā)回。
EchoClient - 響應服務客戶端程序,負責連接響應服務器。其中
messages
- 定義了一個要發(fā)送的消息列表,每次發(fā)送一個消息,知道列表為空為止。handle_read()
- 處理接收到的數(shù)據(jù),這里把收到的數(shù)據(jù)打印的終端上。writable()
- 判斷是否有數(shù)據(jù)可以向服務器端發(fā)送。handle_write()
- 當writable()函數(shù)返回True時,寫入數(shù)據(jù)。
EchoServerThread - 用來啟動服務器端程序的線程。
EchoClientThread - 用來啟動客戶端端程序的線程。
測試
運行上面的測試代碼,可以看到服務器和客戶端建立了連接后,響應了客戶端發(fā)送來的10個數(shù)字,然后關閉了連接。
Incoming connection from ('127.0.0.1', 51424)
1
2
3
4
5
6
7
8
9
10
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
python正則爬取某段子網(wǎng)站前20頁段子(request庫)過程解析
這篇文章主要介紹了python正則爬取某段子網(wǎng)站前20頁段子(request庫)過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-08-08pytorch教程之網(wǎng)絡的構(gòu)建流程筆記
這篇文章主要介紹了pytorch教程中網(wǎng)絡的構(gòu)建流程,文中附含了詳細的示例代碼流程,有需要的朋友可以借鑒參考下,希望可以有所幫助2021-09-09