From c6e4ea25d128af9e8fa3c490a158b629ac4e3171 Mon Sep 17 00:00:00 2001 From: Tobias Kunze Date: Sat, 5 Nov 2016 12:27:16 +0100 Subject: [PATCH] Respond with a code when closing a connection Regards django/channels#414 --- daphne/http_protocol.py | 7 ++++--- daphne/ws_protocol.py | 7 ++++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/daphne/http_protocol.py b/daphne/http_protocol.py index 5b6158f..d3aeb54 100755 --- a/daphne/http_protocol.py +++ b/daphne/http_protocol.py @@ -265,7 +265,6 @@ class WebRequest(http.Request): }) - class HTTPProtocol(http.HTTPChannel): requestFactory = WebRequest @@ -323,11 +322,13 @@ class HTTPFactory(http.HTTPFactory): protocol.serverSend(message["bytes"], True) if message.get("text", None): protocol.serverSend(message["text"], False) - if message.get("close", False): + + closing_code = message.get("close", False) + if closing_code: if protocol.state == protocol.STATE_CONNECTING: protocol.serverReject() else: - protocol.serverClose() + protocol.serverClose(code=closing_code) else: raise ValueError("Cannot dispatch message on channel %r" % channel) diff --git a/daphne/ws_protocol.py b/daphne/ws_protocol.py index 60f7ace..b57f047 100755 --- a/daphne/ws_protocol.py +++ b/daphne/ws_protocol.py @@ -94,7 +94,7 @@ class WebSocketProtocol(WebSocketServerProtocol): # so drop the connection. self.muted = True logger.warn("WebSocket force closed for %s due to connect backpressure", self.reply_channel) - # Send code 1013 "try again later" with close. + # Send code 503 "Service Unavailable" with close. raise ConnectionDeny(code=503, reason="Connection queue at capacity") else: self.factory.log_action("websocket", "connecting", { @@ -187,11 +187,12 @@ class WebSocketProtocol(WebSocketServerProtocol): else: self.sendMessage(content.encode("utf8"), binary) - def serverClose(self): + def serverClose(self, code=True): """ Server-side channel message to close the socket """ - self.sendClose() + code = 1000 if code is True else code + self.sendClose(code=code) def onClose(self, wasClean, code, reason): self.cleanup()