twisted tcp 客户端重连

在工业应用(物联网中)往往需要一些 tcp作为客户端去连接服务器,成功连接后对物联网设备进行操作,但是如果因为硬件的一些原因可能会出实现重新上电, 连接断开, 所以需要重连接的一些设备的服务器, 而python的twisted的对客户端重联设计的比较友好. 

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()

转载于:https://my.oschina.net/u/198124/blog/1927651

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值