twisted tcp 客戶端重連

在工業應用(物聯網中)每每須要一些 tcp做爲客戶端去鏈接服務器,成功鏈接後對物聯網設備進行操做,可是若是由於硬件的一些緣由可能會出實現從新上電, 鏈接斷開, 因此須要重鏈接的一些設備的服務器, 而python的twisted的對客戶端重聯設計的比較友好. python

from twisted.internet.protocol import Protocol
from twisted.internet import reactor
from twisted.internet.protocol import ReconnectingClientFactory
from apscheduler.schedulers.twisted import TwistedScheduler

conns = {}
 
class MyProtocol(Protocol):
	def __init__(self):
		self.id = 0
		self.ip = None


	def dataReceived(self, data):
		pass

	def connectionLost(self, reason):
		if self.id in conns:
			del conns[self.id]

	def connectionMade(self):
		print self.transport.getPeer().host
		self.ip = self.transport.getPeer().host
		self.id = 0
		conns[self.id] = self
 
class MyClientFactory(ReconnectingClientFactory):
	def startedConnecting(self, connector):
		print 'Started to connect.'

	def buildProtocol(self, addr):
		print 'Connected.'
		print 'Resetting reconnection delay'
		self.resetDelay()
		return MyProtocol()

	def clientConnectionLost(self, connector, reason):
		print 'Lost connection.  Reason:', reason
		ReconnectingClientFactory.clientConnectionLost(self, connector, reason)

	def clientConnectionFailed(self, connector, reason):
		print 'Connection failed. Reason:', reason
		ReconnectingClientFactory.clientConnectionFailed(self, connector,reason)

def sendcommand():
	for k, v in conns.iteritems():
		try:
			v.transport.write("AT+GPI=?\r\n")
		except Exception as e:
			print e.message


if __name__ == '__main__':
	
	reactor.connectTCP('127.0.0.1', 5000, MyClientFactory())
	reactor.connectTCP('127.0.0.1', 5000, MyClientFactory())
	scheduler = TwistedScheduler()
	scheduler.add_job(sendcommand, 'interval',seconds=3)
	scheduler.start()
	reactor.run()
相關文章
相關標籤/搜索