在工业应用(物联网中)往往需要一些 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()