希望讀者具有一定的socket基礎,如果沒有接觸過,請參考socket document手冊。你也可以在public git repository下載源代碼參考,或是使用git或其他的版本管理軟件clone出一份代碼,如下:
- git clone git://github.com/jdavisp3/twisted-intro.git
如果你比較怕麻煩,可以在LinuxIDC.com進行下載,下載地址:
免費下載地址在 http://linux.linuxidc.com/
用戶名與密碼都是www.linuxidc.com
具體下載目錄在 /2012年資料/5月/26日/Python使用Twisted總結/
下載完之後,twisted-info中有一個slow server的demo,大家可以用如下方式運行下,看下效果——緩慢的詩。
- [root@localhost twisted-intro]# python blocking-server/slowpoetry.py --num-bytes 50 --delay 5 --port 51296 poetry/ecstasy.txt
- [root@localhost twisted-intro]# nc localhost 51296
如果一切正常的話,你會看到一條小詩被每次輸出一些字節,一旦這首小詩被完全生產出來,服務器會斷開連接。
除此之外,你可以嘗試再打開一個新的Client去連接Server,新打開的Client必須等待第一個Client被處理完纔會接收信息,的確是一首緩慢的詩^_^
在上面的例子中,客戶端是阻塞的,現在我們分別運行三個不同任務的客戶端,去連接三個不同的服務器,看下效果,如下:
- [root@localhost twisted-intro]# python blocking-server/slowpoetry.py --port 10000 poetry/ecstasy.txt --num-bytes 30
- Serving poetry/ecstasy.txt on port 10000.
- [root@localhost twisted-intro]# python blocking-server/slowpoetry.py --port 10001 poetry/fascination.txt
- Serving poetry/fascination.txt on port 10001.
- [root@localhost twisted-intro]# python blocking-server/slowpoetry.py --port 10002 poetry/science.txt
- Serving poetry/science.txt on port 10002.
- [root@localhost twisted-intro]# python blocking-client/get-poetry.py 10000 10001 10002
- Task 1: get poetry from: 127.0.0.1:10000
- Task 1: got 3003 bytes of poetry from 127.0.0.1:10000 in 0:00:10.122140
- Task 2: get poetry from: 127.0.0.1:10001
- Task 2: got 615 bytes of poetry from 127.0.0.1:10001 in 0:00:06.212043
- Task 3: get poetry from: 127.0.0.1:10002
- Task 3: got 653 bytes of poetry from 127.0.0.1:10002 in 0:00:06.613744
- Got 3 poems in 0:00:22.947927
注意觀察,以上任務是一個一個順序運行的,至於產生阻塞的原因也很簡單,主要在for循環遍歷的時候,是一個任務一個任務順序遍歷的。
- Task 1: got 30 bytes of poetry from 127.0.0.1:10000
- Task 2: got 10 bytes of poetry from 127.0.0.1:10001
- Task 3: got 10 bytes of poetry from 127.0.0.1:10002
- Task 1: got 30 bytes of poetry from 127.0.0.1:10000
- Task 2: got 10 bytes of poetry from 127.0.0.1:10001
- Task 3: got 10 bytes of poetry from 127.0.0.1:10002
- ……
- Task 2 finished
- Task 3: got 10 bytes of poetry from 127.0.0.1:10002
- Task 1: got 30 bytes of poetry from 127.0.0.1:10000
- Task 3: got 10 bytes of poetry from 127.0.0.1:10002
- Task 1: got 30 bytes of poetry from 127.0.0.1:10000
- ……
- Task 3 finished
- Task 1: got 30 bytes of poetry from 127.0.0.1:10000
- Task 1: got 30 bytes of poetry from 127.0.0.1:10000
- ……
- Task 1 finished
- Task 1: 3003 bytes of poetry
- Task 2: 615 bytes of poetry
- Task 3: 653 bytes of poetry
- Got 3 poems in 0:00:10.118896
注意這次任務執行的順序,是交替的。從時間的角度來講,異步的時間比同步的時間快很多。雖然異步的客戶端也存在I/O阻塞情況,但通過交替執行可以減少阻塞時間,從而加快運行時間。