I want to send a message over a channel using Django Channels. This is what I'm doing. I create a consumer first. I'm able to echo back the received messages. However, not able to send messages to a specific channel/group.
class Consumer(AsyncJsonWebsocketConsumer): """Consumer."""
def _get_connection_id(self): return ''.join(e for e in self.channel_name if e.isalnum())
# Adding current to group. await self.channel_layer.group_add( user_id, connection_id, )
async def disconnect(self, close_code): """Remove the connection and decrement connection_count in DB.""" connection_id = self._get_connection_id() user_id = str(self.scope['user'].user_id)
# Dropping from group. await self.channel_layer.group_discard( user_id, connection_id, )
async def receive_json(self, data, **kwargs): """Receive messages over socket.""" resp = data # I'm able to echo back the received message after some processing. await self.send(json.dumps(resp, default=str))
# This does not works. def send_to_connection(connection_id, data): """Send the data to the connected socket id.""" return get_channel_layer().group_send(connection_id, data)
Now when I try to send a message, the connected socket does not receives the message.