希望读者具有一定的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阻塞情况,但通过交替执行可以减少阻塞时间,从而加快运行时间。