【发布时间】:2021-01-03 01:07:08
【问题描述】:
我想使用 Django 频道通过频道发送消息。我就是这样做的。
我首先创建一个消费者。我能够回显收到的消息。但是,无法将消息发送到特定频道/组。
class Consumer(AsyncJsonWebsocketConsumer):
"""Consumer."""
def _get_connection_id(self):
return ''.join(e for e in self.channel_name if e.isalnum())
async def connect(self):
scope = self.scope
user_id = str(scope['user'].user_id)
connection_id = self._get_connection_id()
# Adding connection to DB.
obj = UserConnection.add(connection_id=connection_id, user_id=user_id)
# Accept the connection
await self.accept()
# 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)
UserConnection.drop(connection_id=connection_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)
现在当我尝试发送消息时,连接的套接字没有收到消息。
>>> connection_id = UserConnection.objects.get(user_id=user_id).connection_id
>>> send_to_connection(connection_id, {'a':1})
# returns <coroutine object RedisChannelLayer.group_send at 0x109576d40>
代码有什么问题?
【问题讨论】:
标签: django sockets websocket django-channels