2017-01-19 45 views
0

我有一系列的客户端需要通过ws协议不断连接到我的服务器。由于许多不同的原因,连接偶尔会下降。这是可以接受的,但是当它发生时,我希望我的客户重新连接。高速公路+扭曲的重新连接

目前我的临时解决方法是让父进程启动客户端,当它检测到连接丢失时,终止它(客户端从不处理任何关键数据,不会对sigkill产生副作用),并重新创建一个新客户端。虽然这样做的工作,我非常希望解决实际问题。

这大致是我的客户:

from autobahn.twisted.websocket import WebSocketClientProtocol, WebSocketClientFactory 
from twisted.internet import reactor 
from threading import Thread 
from time import sleep 


class Client: 
    def __init__(self): 
     self._kill = False 

     self.factory = WebSocketClientFactory("ws://0.0.0.0") 
     self.factory.openHandshakeTimeout = 60 # ensures handshake doesnt timeout due to technical limitations 
     self.factory.protocol = self._protocol_factory() 

     self._conn = reactor.connectTCP("0.0.0.0", 1234, self.factory) 
     reactor.run() 

    def _protocol_factory(self): 
     class ClientProtocol(WebSocketClientProtocol): 
      def onConnect(self, response): 
       Thread(target=_self.mainloop, daemon=True).start() 

      def onClose(self, was_clean, code, reason): 
       _self.on_cleanup() 

     _self = self 
     return ClientProtocol 

    def on_cleanup(self): 
     self._kill = True 
     sleep(30) 
     # Wait for self.mainloop to finish. 
     # It is guaranteed to exit within 30 seconds of setting _kill flag 
     self._kill = False 
     self._conn = reactor.connectTCP("0.0.0.0", 1234, self.factory) 

    def mainloop(self): 
     while not self._kill: 
      sleep(1) # does some work 

该代码使得客户能正常工作,直到第一个连接中断,此时将其尝试重新连接。在这个过程中没有发生任何例外情况,看起来一切正常,客户端,onConnect被调用,并且新的mainloop启动,但服务器从未收到第二次握手。尽管如此,客户似乎认为认为它已连接。

我在做什么错?为什么会发生这种情况?

回答

0

我不是一个扭曲的专家,不能真正告诉你做错了什么,但我目前正在与一个项目中的高速公路工作,我解决了使用ReconnectingClientFactory重新连接问题。也许你想检查一些examples与Autobahn使用ReconnectingClientFactory。