在执行之前是否有可能测试连接是否仍然存在transport.write()
?
我修改了 simpleserv/simpleclient 示例,以便Protocol.transport
每 5 秒发送(写入)一条消息。连接是持久的。
断开我的wifi时,它仍然会写入传输(当然消息不会到达另一端)但不会引发错误。再次启用 wifi 时,消息正在传递,但下一次发送消息的尝试失败(并被Protocol.connectionLost
调用)。
这里又是按时间顺序发生的事情:
- 发送消息建立连接,消息被传递。
- 禁用 wifi
- 发送消息写入
transport
,不抛出错误,消息未到达 - 启用无线网络
- 3.发送的消息到达
- 发送消息导致
Protocol.connectionLost
通话
如果我可以写入传输,在执行步骤 6 之前知道会很高兴。有什么办法吗?
服务器:
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from twisted.internet import reactor, protocol
class Echo(protocol.Protocol):
"""This is just about the simplest possible protocol"""
def dataReceived(self, data):
"As soon as any data is received, write it back."
print
print data
self.transport.write(data)
def main():
"""This runs the protocol on port 8000"""
factory = protocol.ServerFactory()
factory.protocol = Echo
reactor.listenTCP(8000,factory)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
客户:
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
An example client. Run simpleserv.py first before running this.
"""
from twisted.internet import reactor, protocol
# a client protocol
counter = 0
class EchoClient(protocol.Protocol):
"""Once connected, send a message, then print the result."""
def connectionMade(self):
print 'connectionMade'
def dataReceived(self, data):
"As soon as any data is received, write it back."
print "Server said:", data
def connectionLost(self, reason):
print "connection lost"
def say_hello(self):
global counter
counter += 1
msg = '%s. hello, world' %counter
print 'sending: %s' %msg
self.transport.write(msg)
class EchoFactory(protocol.ClientFactory):
def buildProtocol(self, addr):
self.p = EchoClient()
return self.p
def clientConnectionFailed(self, connector, reason):
print "Connection failed - goodbye!"
def clientConnectionLost(self, connector, reason):
print "Connection lost - goodbye!"
def say_hello(self):
self.p.say_hello()
reactor.callLater(5, self.say_hello)
# this connects the protocol to a server running on port 8000
def main():
f = EchoFactory()
reactor.connectTCP("REMOTE_SERVER_ADDR", 8000, f)
reactor.callLater(5, f.say_hello)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()