Chinaunix

标题: 关于twisted的问题.. [打印本页]

作者: kwoarang    时间: 2010-06-24 17:18
标题: 关于twisted的问题..
最近在学习twisted, 碰到几个问题请大家帮忙看看.

一个简单的客户端
#!/usr/bin/env python
#coding: utf-8

from twisted.internet import reactor, protocol
from twisted.protocols.basic import LineReceiver

class sendmsgProtocol(LineReceiver):
    def connectionMade(self):
        print "sending %s" % str(self.factory.id)
        self.transport.write(str(self.factory.id)+'\r\n')

    def lineReceived(self,data):
        print "received ",data
        self.transport.loseConnection()

class sendmsgFactory(protocol.ClientFactory):
    protocol = sendmsgProtocol
    def __init__(self,id):
        self.id=id

if __name__ == '__main__':
        reactor.connectTCP("localhost",8000,sendmsgFactory(1))
        reactor.run()

运行以后服务器端可以收到消息,并返回值, 客户端也能收到返回值, 但是运行以后程序不退出, 卡住了, 必须用ctrl-c才能退出,
这是怎么回事啊, 我想让客户端收到消息, 断开连接后脚本就退出, 请多多帮忙.
作者: luffy.deng    时间: 2010-06-24 18:39
调用了 reactor.stop ()才会停止。
作者: kwoarang    时间: 2010-06-25 09:12
我尝试过, 在脚本后面加了
time.sleep(5)
reactor.stop()
这样会出异常,
2010-06-24 22:56:19+0800 [-] Traceback (most recent call last):
2010-06-24 22:56:19+0800 [-] File "client.py", line 68, in <module>
2010-06-24 22:56:19+0800 [-] reactor.stop()
2010-06-24 22:56:19+0800 [-] File "/usr/local/python2.6.2/lib/python2.6/site-packages/Twisted-10.0.0-py2.6-linux-i686.egg/tw
isted/internet/base.py", line 552, in stop
2010-06-24 22:56:19+0800 [-] "Can't stop reactor that isn't running.")
2010-06-24 22:56:19+0800 [-] twisted.internet.error.ReactorNotRunning: Can't stop reactor that isn't running.

说明这时reactor已经停止了,  甚至在后面加sys.exit(0)也一样, 必须按ctrl-c才能退出.
作者: luffy.deng    时间: 2010-06-25 09:44
本帖最后由 luffy.deng 于 2010-06-25 09:48 编辑

回复 3# kwoarang

不是这么用的。异步的  你得在某个事件的callback里调用 reactor.stop()。当事件发生是就会退出。




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2