I am using following twisted client code to connect to server which sends data to server after every 3 seconds and if their is disconnection client will again try to connect server after every 10 every. This client code is running 24hrs. But I have observed that in long run the client fails to send data to server even though server in online. I have to restart this client code after killing old client process to make it work again. Following is the code I am using:
#!/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()
What can be the problem for failure of this code in the long run?
I noticed logging is done when when connections fail or are lost. You might be doing this in your actual code. The reason
argument gives a bit of context as to why things have failed so it may be worth it to log those. Also you should resetDelay()
when the connection is lost/fails as opposed to running it in buildProtocol()
.
If doing the above still doesn't help uncover the issue on the client side, then try to add some logging on the server side (if possible). There are literally infinite reasons why a connection "just stops" and it can very from environment to environment. If all else fails then you'll need to use something like wireshark.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.