From cad63451f8f9bc0595f4c58154cc98cd188df6dc Mon Sep 17 00:00:00 2001 From: Andrew Godwin Date: Sun, 12 Mar 2017 21:03:25 -0700 Subject: [PATCH] Expand more on accepting connections --- docs/concepts.rst | 2 ++ docs/getting-started.rst | 11 +++++++++++ 2 files changed, 13 insertions(+) diff --git a/docs/concepts.rst b/docs/concepts.rst index 83a3b12..f942922 100644 --- a/docs/concepts.rst +++ b/docs/concepts.rst @@ -235,6 +235,8 @@ abstraction as a core concept called Groups:: def ws_connect(message): # Add to reader group Group("liveblog").add(message.reply_channel) + # Accept the connection request + message.reply_channel.send({"accept": True}) # Connected to websocket.disconnect def ws_disconnect(message): diff --git a/docs/getting-started.rst b/docs/getting-started.rst index c11af1c..422e5dd 100644 --- a/docs/getting-started.rst +++ b/docs/getting-started.rst @@ -165,13 +165,20 @@ disconnect, like this:: # Connected to websocket.connect def ws_add(message): + # Accept the incoming connection message.reply_channel.send({"accept": True}) + # Add them to the chat group Group("chat").add(message.reply_channel) # Connected to websocket.disconnect def ws_disconnect(message): Group("chat").discard(message.reply_channel) +.. note:: + You need to explicitly accept WebSocket connections if you override connect + by sending ``accept: True`` - you can also reject them at connection time, + before they open, by sending ``close: True``. + Of course, if you've read through :doc:`concepts`, you'll know that channels added to groups expire out if their messages expire (every channel layer has a message expiry time, usually between 30 seconds and a few minutes, and it's @@ -204,7 +211,9 @@ get the message. Here's all the code:: # Connected to websocket.connect def ws_add(message): + # Accept the connection message.reply_channel.send({"accept": True}) + # Add to the chat group Group("chat").add(message.reply_channel) # Connected to websocket.receive @@ -559,6 +568,8 @@ consumer above to use a room based on URL rather than username:: def ws_add(message, room): # Add them to the right group Group("chat-%s" % room).add(message.reply_channel) + # Accept the connection request + message.reply_channel.send({"accept": True}) In the next section, we'll change to sending the ``room`` as a part of the WebSocket message - which you might do if you had a multiplexing client -