I need to setup a WebSocket server using Channels ==3.0.4 and Django ==3.2
First of all, I’m using the default channel “InMemoryChannelLayer”, I created a consumer class and I tested my connection by using a simple javascript file as a client and it worked well.
I can send and receive messages between my consumer and this javascript file.
Now, I want to send a message through this channel outside my consumer.
The function is outside the consumer
async_to_sync(channel_layer.send)(
“my_channel”,
{
“type”: “notify”,
…}
. I want to call the async_to_sync outside the consumer. But the problem is that this function does not invoke the method “notify” in the consumer.
it can not know the consumer that should be invoked.
It seems that the problem is with the channel_name .Can anyone here know what I 'm missing?
this is my consumer.py
from channels.generic.websocket import AsyncWebsocketConsumer
from channels.layers import InMemoryChannelLayer
channel_layer = InMemoryChannelLayer()
class Consumer(AsyncWebsocketConsumer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
async def connect(self, *args, **kwargs):
await super().accept()
async def receive(self, text_data=None, bytes_data=None, **kwargs):
message = json.loads(text_data)
await self.send(json.dumps({'message': message}))
async def disconnect(self, *args, **kwargs):
await self.close(*args)
# @channel_layer.receive
async def notify(self, event):
await self.send(text_data=json.dumps(event["text"]))
channel_name = "my_channel"
My function out side consumer.py
channel_layer = get_channel_layer()
async_to_sync(channel_layer.send)(
"my_channel",
{
"type": "notify",
"text": "Hello,Listen here world!"
},
)
and in my asgi.py:
application = ProtocolTypeRouter({
'http': get_asgi_application(),
"websocket": URLRouter(routing.websocket_urlpatterns),
"channel": ChannelNameRouter({
"my_channel": Consumer,
})
thanks