3

As I'm new to websockets, Is it possible to create multiple websocket.receive routes for different consumers with different groups?

app/consumers.py
# First receiver
def ws_receive1(message):
    Group(
       'Group1',
       channel_layer=message.channel_layer
       ).send({'text': "receiver1"})

def ws_receive2(message):
    Group(
       'Group2',
       channel_layer=message.channel_layer
       ).send({'text': "receiver2"})

# routing.py
channel_routing = [
    route("websocket.connect", consumers.ws_connect1),
    route("websocket.disconnect", consumers.ws_disconnect1),
    route("websocket.receive", consumers.ws_receive1),

    route("websocket.connect", consumers.ws_connect2),
    route("websocket.disconnect", consumers.ws_disconnect2),
    route("websocket.receive", consumers.ws_receive2),
]

Any advise on it?

1 Answer 1

2

Here is my implementation for the above. Please suggest if further modifications required.

#app1/routing.py

from channels.routing import route
from . import consumers

post_websocket = [
    route("websocket.connect", consumers.websocket_connect),
    route("websocket.disconnect", consumers.websocket_disconnect)
]

vote_websocket = [
    route("websocket.connect", consumers.websocket_voteconnect),
    route("websocket.receive", consumers.ws_updatevotes),
    route("websocket.disconnect", consumers.websocket_votedisconnect)
]


# myproject/routing.py
from channels import include

channel_routing = [
    include("app1.routing.post_websocket", path=r"^/app1/post/notification"),
    include("app1.routing.vote_websocket", path=r"^/app1/vote/notification"),
]

You can find the code here asifpy/channels-examples

Sign up to request clarification or add additional context in comments.

2 Comments

this is not working for me... is this the official way to do it? here they don't use the path to split actions up but i think this should work as well? github.com/andrewgodwin/channels-examples
This answer does not address the problem. Multiple consumers on a single channel do not currently make sense - you are defining different functions to deal with the same incoming messages. Which function handles the message is conceptually arbitrary. To split the websocket traffic coming in on one of those three channels out to different functions you have to work within the websocket.xxx consumers. Perhaps by further parsing the path there. See groups.google.com/forum/#!topic/django-developers/n3cC9AWwTXA for more information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.