0

我的程序中有几个房间。每个用户都可以连接到这些房间并发送消息。对于每个房间,我都有一组。我想在连接功能中为这些组指定房间名称。但我不知道如何在连接功能中发送房间名称。

@channel_session_user_from_http
def chat_connect(message):       
   message.reply_channel.send({'accept': True})

@touch_presence
@channel_session_user
def chat_receive(message):
    data = json.loads(message['text'])
    myRoom = data['room']
    messageChat = data['messagechat']

    if not message.user.is_authenticated():        
        return

    Group(myRoom).add(message.reply_channel)
    Room_channels_presence.objects.add(myRoom,   message.reply_channel.name, message.user)
    message.channel_session['room'] = myRoom

    #store in db
    try:
        room = Room.objects.get(slug=myRoom)
        message_model = Message(
                            user = message.user,
                            room = room,
                            text = messageChat
                        )
        message_model.save()
    except:
        pass


    my_dict = {
        'user': message.user.username,
        'messagechat': messageChat
    }
    Group(myRoom).send({'text': json.dumps(my_dict)})
4

1 回答 1

0

为了发送房间的名字。我曾经在 js 文件中打开函数。当我们第一次连接到一个房间时,实际上是为 websocket 运行 onopen 函数。我们可以在 onopen 函数的主体中发送我们的文本。像这样:

chatsock.onopen = function() {              
    //in order to set room' name
    var message = {
        messagechat: "",
        room: roomSlug
    }       
    chatsock.send(JSON.stringify(message));
}

然后,我们可以在 consumer.py 的接收函数中接收此文本:

def chat_receive(message):
    data = json.loads(message['text'])
    myRoom = data['room']
    messageChat = data['messagechat']

    if not message.user.is_authenticated():        
        return    

    Group(myRoom).add(message.reply_channel)
    Room_channels_presence.objects.add(myRoom, message.reply_channel.name, message.user)
    message.channel_session['room'] = myRoom

   #if seding message came from onopen function in realtime.js
   #we just want to create a session for room's name
   if not messageChat:
       print('notttttttttt')
       return
于 2017-11-27T05:36:48.420 回答