我使用下面的扭曲客户端代码连接到服务器,服务器每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()
从长远来看,这段代码失败的原因是什么?在
我注意到日志记录是在连接失败或丢失时完成的。您可能正在实际代码中执行此操作。
reason
参数提供了一点上下文,说明为什么事情失败了,因此记录这些可能是值得的。另外,当连接丢失/失败时,您应该resetDelay()
,而不是在buildProtocol()
中运行它。在如果执行上述操作仍然不能帮助发现客户端的问题,那么尝试在服务器端添加一些日志记录(如果可能)。事实上,有无限的原因可以解释为什么一个连接“只是停止”,而且它可以从一个环境到另一个环境。如果其他方法都失败了,那么你需要使用类似wireshark的东西。在
相关问题 更多 >
编程相关推荐