简单的Twisted服务器无法通过定时器写入

1 投票
1 回答
566 浏览
提问于 2025-04-16 02:21

我正在学习Python和Twisted,但我搞不懂为什么这个简单的服务器不工作。当我从一个定时器中调用self.transport.write时,它没有任何反应。我没有收到任何错误信息。希望能得到一些帮助,非常感谢!

from twisted.internet.protocol import Factory, Protocol
from twisted.internet import reactor
from threading import Timer

class proto(Protocol):

    def saySomething(self):
        self.transport.write('hello there\r\n')

    def connectionMade(self):
        Timer(5, self.saySomething).start()

class theFactory(Factory):

    protocol = proto

reactor.listenTCP(8007, theFactory())
reactor.run()

1 个回答

2

我自己搞定了。

来自 http://twistedmatrix.com/documents/current/core/howto/threading.html 的内容:

在Twisted中,大部分代码都不是线程安全的。举个例子,从一个协议向传输写数据,这个操作就不是线程安全的。

不过还是谢谢大家!

撰写回答