django渠道消费者消费1个电话2次

p1tboqfb  于 2021-06-09  发布在  Redis
关注(0)|答案(1)|浏览(477)

我使用drf3.11.0和channels2.4.0的组合来实现一个后端,它托管在1dyno上的heroku上,附带了redis资源。我的react前端有一个套接字,它成功地从后端服务器发送/接收数据。
我有一个问题,任何信息发送回前端通过插座被发送两次。我已经确认了 console.log 前端只与后端ping了一次。我可以通过 print() 函数只调用的api调用的内部 async_to_sync(channel_layer.group_send) 也有一次。问题来自我的消费者-当我使用 print(self.channel_name) 内部 share_document_via_videocall() ,我可以看到两个不同的例子 self.channel_name 有人打电话给他们( specific.AOQenhTn!fUybdYEsViaP 以及 specific.AOQenhTn!NgtWxuiHtHBw . 似乎消费者已经连接到两个不同的渠道,但我不知道为什么。当我把 print() 我的声明 connect() 我只看到它经过一次连接过程。
如何确保仅连接到一个通道?
settings.py :

CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            #"hosts": [('127.0.0.1', 6379)],
            "hosts": [(REDIS_HOST)],
        },
    },
}

消费者:

import json
from asgiref.sync import async_to_sync
from channels.db import database_sync_to_async

from channels.generic.websocket import AsyncWebsocketConsumer
from rest_framework.authtoken.models import Token
from django.contrib.auth.models import AnonymousUser
from .exceptions import ClientError
import datetime
from django.utils import timezone

class HeaderConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        print("connecting")

        await self.accept()
        print("starting")
        print(self.channel_name)
        await self.send("request_for_token")

    async def continue_connect(self):
        print("continuing")
        print(self.channel_name)

        await self.get_user_from_token(self.scope['token'])

        await self.channel_layer.group_add(
            "u_%d" % self.user['id'],
            self.channel_name,
        )
        #... more stuff

    async def disconnect(self, code):
        await self.channel_layer.group_discard(
            "u_%d" % self.user['id'],
            self.channel_name,
        )

    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        if 'token' in text_data_json:
            self.scope['token'] = text_data_json['token']
            await self.continue_connect()

    async def share_document_via_videocall(self, event):

        # Send a message down to the client
        print("share_document received")
        print(event)
        print(self.channel_name)
        print(self.user['id'])

        await self.send(text_data=json.dumps(
            {
                "type": event['type'],
                "message": event["message"],
            },
        ))

    @database_sync_to_async
    def get_user_from_token(self, t):
        try:
            print("trying token" + t)
            token = Token.objects.get(key=t)
            self.user = token.user.get_profile.json()
        except Token.DoesNotExist:
            print("failed")
            self.user = AnonymousUser()

rest api调用:

class ShareViaVideoChat(APIView):
    permission_classes = (permissions.IsAuthenticated,)

    def post(self, request, format=None):
        data = request.data
        recipient_list = data['recipient_list']

        channel_layer = get_channel_layer()
        for u in recipient_list:
            if u['id'] != None:
                print("sending to:")
                print('u_%d' % u['id'])
                async_to_sync(channel_layer.group_send)(
                    'u_%d' % u['id'],
                    {'type': 'share_document_via_videocall',
                     'message': {
                             'document': {'data': {}},
                             'sender': {'name': 'some name'}
                         }
                     }
                )

        return Response()
4xy9mtcn

4xy9mtcn1#

关于您获得不同频道名称的呼叫,您确定您的前端没有两次连接到消费者吗?在浏览器中签入调试控制台。

相关问题