def connect(self, factory):
"""Connect with WebSocket over TCP or SSL."""
websocketsFactory = WebSocketsClientFactory()
websocketsFactory.setHandshake(self._handshake)
websocketsFactory.wrappedFactory = factory
endpoint = self._getEndpoint()
deferred = endpoint.connect(websocketsFactory)
protocolReference = [] # Trick to save a reference to the protocol
def onConnectFailure(failure):
# The connection failed (either due to an error or due to
# the low-level endpoint timeout). Let's cancel our own
# timeout and propagate the error.
call.cancel()
return failure
def onConnectSuccess(protocol):
# We're connected, now let's wait for the handshake
protocolReference.append(protocol)
return protocol.deferred.addBoth(onHandshakeFinished)
def onHandshakeFinished(value):
# The handshake has finished, either successfully or not. Unless
# this is a timeout failure itself, let's cancel the timeout call.
if not isinstance(value, Failure) or not value.check(TimeoutError):
call.cancel()
return value
def onTimeout():
# If we got here it means that the handshake has timed out, because
# if the connection times out we cancel our own timeout (see
# onConnectFailure). Let's abort the connection and errback.
[protocol] = protocolReference
protocol.abortHandshake(TimeoutError())
call = self._reactor.callLater(self._timeout, onTimeout)
deferred.addErrback(onConnectFailure)
deferred.addCallback(onConnectSuccess)
return deferred
评论列表
文章目录