如何在Django频道的连接功能中发送房间名称

时间:2017-11-26 15:54:29

标签: django django-channels django-channels-presence

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

@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)})

1 个答案:

答案 0 :(得分:0)

为了发送房间的名字。我以前在js文件中使用onopen函数。 当我们第一次连接到房间时,事实上,我们为websocket运行onopen功能。 我们可以在onopen函数体中发送我们的文本。像这样:

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

然后,我们可以在consumers.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