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
이 시작되지만 서버는 그 두 번째 핸드 셰이크를 수신하지 못합니다. 클라이언트는 라고 생각 합니다만,라고 생각합니다.
내가 뭘 잘못하고 있니? 왜 이런 일이 일어날 수 있습니까?