【问题标题】:twisted client stops connecting to server扭曲的客户端停止连接到服务器
【发布时间】:2016-10-20 07:34:58
【问题描述】:

我正在使用以下扭曲的客户端代码连接到服务器,该服务器每 3 秒后向服务器发送数据,如果它们断开连接,客户端将在每 10 秒后再次尝试连接服务器。此客户端代码 24 小时运行。但我观察到,从长远来看,即使服务器在线,客户端也无法将数据发送到服务器。我必须在杀死旧的客户端进程后重新启动这个客户端代码才能让它再次工作。以下是我正在使用的代码:

#!/usr/bin/python
import binascii
from functools import partial

from twisted.internet import reactor, protocol, task
from twisted.internet.protocol import ReconnectingClientFactory

connection = None
lineNumber = 5
displayIP = '192.168.0.207'
l = None

#MAIN CLASSES FOR TCP CLIENT
class EchoClient(protocol.Protocol):
    def connectionMade(self):
        global connection
        connection = self.transport
        startClock(self)
    def dataReceived(self, data):
        self.print_message(data)

    def print_message(self, data):
        print " message received"

class EchoFactory(protocol.ReconnectingClientFactory):
    protocol = EchoClient
    maxDelay = 10

    def startedConnecting(self, connector):
        pass    

    def buildProtocol(self,addr):
        self.resetDelay()
        return EchoClient()

    def clientConnectionLost(self, conn, reason):
        global connection
        connection = None
        ReconnectingClientFactory.clientConnectionLost(self, conn, reason)

    def clientConnectionFailed(self, conn, reason):
        global connection
        connection = None
        ReconnectingClientFactory.clientConnectionFailed(self, conn, reason)


#TO SEND to server
def sendToServer(self):
    if connection:
        sendPackets(self)
    else: pass

#clock after every 3 seconds packet is send to server
def startClock(self):
    l = task.LoopingCall(partial(sendToServer,self))
    l.start(3.0)

#send current status to server
def sendPackets(self):
    try:
        self.transport.write((binascii.unhexlify(sendString)))
    except Exception, ex: pass

#THIS CONNECTS CLIENT TO server
def main():
    f = EchoFactory()
    reactor.connectTCP(displayIP, 8004, f)
    reactor.run()

#MAIN FUNCTION CALLING MODULE
if __name__ == '__main__':
    main()

从长远来看,这段代码失败的问题是什么?

【问题讨论】:

    标签: python python-2.7 twisted


    【解决方案1】:

    我注意到当连接失败或丢失时会完成日志记录。您可能会在实际代码中执行此操作。 reason 参数提供了一些关于为什么事情失败的背景信息,因此记录这些可能是值得的。此外,您应该在连接丢失/失败时resetDelay(),而不是在buildProtocol() 中运行它。

    如果执行上述操作仍无法帮助发现客户端的问题,请尝试在服务器端添加一些日志记录(如果可能)。从字面上看,连接“刚刚停止”的原因有很多,而且它可以从一个环境到另一个环境。如果所有其他方法都失败了,那么您将需要使用诸如 wireshark 之类的东西。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-15
      • 2012-06-04
      相关资源
      最近更新 更多