实时聊天:消息发送给错误的用户。 Django频道

时间:2020-06-30 06:08:21

标签: django django-channels

我正在项目中添加聊天功能。我正在显示一个用户列表,当用户单击特定的用户名时,将打开一个聊天框。一切正常。问题是当当前用户发送消息时,它将发送给所有用户。我知道问题的原因。我不知道解决方案。

<script>
$(".user-name-container").click(function(){
        
        var less_num = "variable"
        var big_num = "variable"

        var ws_scheme = window.location.protocol == "https:" ? "wss://" : "ws://";
        window.chatCustomerSocket = new ReconnectingWebSocket(
        ws_scheme + window.location.host +
        '/ws/chat_to_customer/' + big_num +'/'+ less_num + '/');

        <!------- Send message ------->
            $("#input-message-button").click(function(){
                "-----logic------"
                chatCustomerSocket.send(JSON.stringify({
                    'message': "msg",
                    'send_to': "sent_username",
                    'send_by': "self_username",
                }));
            });

            <!------------ Recieve Message ------------>
            chatCustomerSocket.onmessage = function(e) {
                "Recieve Logic"
            };
        });
</script>

当用户单击用户名时,Websocket连接已建立,但先前的连接不会终止。我认为这就是为什么消息会发送给已选择的所有用户的原因。这是消费者:

class ChatToCustomerConsumer(WebsocketConsumer):

    def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['first_user']
        self.user_email = self.scope['url_route']['kwargs']['next_user']
        self.room_group_name = 'chat_customer_%s' % self.room_name + self.user_email
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )

        self.accept()

    def disconnect(self, close_code):
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )

    # Receive message from WebSocket
    def receive(self, text_data):
        first = self.scope['url_route']['kwargs']['first_user']
        last = self.scope['url_route']['kwargs']['next_user']
        chat_name = first + '-' + last
        text_data_json = json.loads(text_data)
        msg = text_data_json['message']
        send_to = text_data_json['send_to']
        send_by = text_data_json['send_by']
        user = User.objects.get(username=send_by)
        Messages.objects.create(message=msg, sent_by=user, chat_name=chat_name)
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': msg,
                'send_to': send_to,
            }
        )

    # Receive message from room group
    def chat_message(self, event):
        message = event['message']
        send_to = event['send_to']
        self.send(text_data=json.dumps({
            'message': message,
            'send_to': send_to,
        }))

0 个答案:

没有答案