1

を実行する前に接続がまだ存在するかどうかをテストする可能性はありtransport.write()ますか?

Protocol.transportメッセージが5 秒ごとに送信される (に書き込まれる) ように、simpleserv/simpleclient の例を変更しました。接続は永続的です。

私のwifiを切断しても、まだトランスポートに書き込みます(もちろん、メッセージは反対側に届きません)が、エラーはスローされません。Wi-Fi を再度有効にすると、メッセージは配信されますが、次のメッセージ送信の試行は失敗します (そしてProtocol.connectionLost呼び出されます)。

ここでも時系列で何が起こるか:

  1. メッセージを送信すると接続が確立され、メッセージが配信されます。
  2. Wi-Fi を無効にする
  3. メッセージを送信すると に書き込みますがtransport、エラーはスローされず、メッセージは届きません
  4. Wi-Fi を有効にする
  5. 3.で送信したメッセージが届く
  6. メッセージを送信する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()
4

1 に答える 1