django 使用 channels 搭建在线客服疑惑

2020-05-14 23:43:58 +08:00
 endpain

版本: python == 3.8.1 Django 3.0.4
channels 2.4.0
channels-redis 2.4.2
疑问如下,因为百度搜索的答案实在是一言难尽,都是千篇一律的一样,根据我的个人理解,和查看官网,在 channels 里面包括官方教程都是着重再讲多人聊天和群组聊天( group ),我想实现的是通过 layim 一对一聊天

整体都能跑通,但是不知道为什么,a 用户发给 b 用户的消息,b 是收不到的,这块我实在是不明白以下几个问题,希望有懂的大神可以指点一下

1 、a 用户发给 b 用户,我如何能给 b 用户去进行推送,

            async_to_sync(self.channel_layer.send)(
                to_user_id,
                {
                    'type': 'chat_messages',  # 调用的发送方法
                    'event':data_json

                }
            )

上面的代码貌似没生效,b 用户是没有收到的

2 、channels 如何能获取当前有几个人在连接,他们存储在 redis 的 channel_name 如何获取?

附上我的代码,感谢~

from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import *
from channels.db import database_sync_to_async
from rest_framework_jwt.authentication import jwt_decode_handler
import json
import redis
import time
from chat import models

pool = redis.ConnectionPool(
    host='localhost',
    port=6379,
    max_connections=10,
    decode_responses=True
)
conn = redis.Redis(connection_pool=pool, decode_responses=True)


class ChatConsumer(WebsocketConsumer):
    chats = {}

    def connect(self):
        try:
            jwt = self.scope['query_string'].decode() #获取 jwt
            if not jwt:
                # 请求存在问题
                raise DenyConnection("jwt 信息错误")
            payload = jwt_decode_handler(jwt)
        except:
            print("jwt 信息错误")

        print(payload)
        self.user_id = str(payload['user_id'])

        async_to_sync(self.channel_layer.group_add)(
            self.user_id,
            self.channel_name
        )
        # ChatConsumer.chats[user_id] = {'self':self,'last_time':int(time.time())}
        self.accept()

    def disconnect(self, close_code):

        async_to_sync(self.channel_layer.group_discard)(
            self.user_id,
            self.channel_name
        )

        ChatConsumer.chats[self.group_name].remove(self)

        self.close()


    def receive(self, text_data):
        data_json = json.loads(text_data)
        type = data_json.get('type') # 类型

        if type == 'chatMessage':
            # 发送消息
            mine_user_id = data_json.get('data').get('mine').get('id') # 发送者 id
            to_user_id = data_json.get('data').get('to').get('id') # 接受者 id
            message = data_json.get('data').get('mine').get('content') #发送内容

            # 接受成功消息,返回结果
            self.send(text_data=json.dumps({
                'server_socket_type': 'MessageReceivedSuccessfully',
                'result': True,
                'time': int(time.time()),
            }))

            async_to_sync(self.channel_layer.send)(
                to_user_id,
                {
                    'type': 'chat_messages',  # 调用的发送方法
                    'event':data_json

                }
            )



1586 次点击
所在节点    Python
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/671826

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX