Reputation: 1743
As far as I know twisted is asynchronous and event driven and someone told me their is no need for timeout. I have to build a server application which will be connected to more than 100 clients which are embedded machines sending data to server every 2 minutes and each packet or data will be of size 238 - 1500 bytes. Thus is real life case tcp will be breaking data into multiple packets so is their any need to implement timeout or twisted will handle such situation. Any advise since I am new twisted. I have following code for my server without timeout. At the end of timeout I just want to discard packet if full packet is not received while connection remains alive.
class Server(LineReceiver):
def connectionMade(self):
self.factory.clients.append(self)
self.setRawMode()
self._peer = self.transport.getPeer()
print 'Connected Client', self._peer
def connectionLost(self, reason):
self.factory.clients.remove(self)
print 'Lost connection from', self._peer
def rawDataReceived(self, data):
inputArray = [ord(inp) for inp in data]
#do something
def main():
"""This runs the protocol on port 8000"""
factory = protocol.ServerFactory()
factory.protocol = Server
factory.clients = []
reactor.listenTCP(8000,factory)
reactor.run()
Upvotes: 4
Views: 3431
Reputation: 414265
As @Ashish Nitin Patil suggested, just cut the connection to implement the timeout:
from twisted.internet import reactor
# ...
def connectionMade(self):
# ... your code
# cancel connection in 2 minutes
reactor.callLater(120, self.transport.loseConnection)
Or
At the end of timeout I just want to discard packet if full packet is not received while connection remains alive.
If you don't want to cancel the connection on timeout then:
from time import time as timer
def connectionMade(self):
# ... your code
self.endtime = timer() + 120 # timeout in 2 minutes
def dataReceived(self, data):
if timer() > self.endtime: # timeout
if not self.have_we_received_full_packet()
return # do nothing (discard data, the connection remains alive)
else:
# timeout happened but we have a full packet, now what?
inputArray = bytearray(data)
#do something
Upvotes: 3