Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
553 views
in Technique[技术] by (71.8m points)

javascript - Django频道:使用sessionStorage使用JavaScript存储用户名时出现问题,更好的存储变量的方法?(Django Channels: issue using sessionStorage to store username with JavaScript, better way to store variable?)

I am using Django Channels to build a chat app.

(我正在使用Django Channels构建聊天应用程序。)

It is not backed by a database and I am trying to handle everything via JavaScript.

(它没有数据库支持,我正在尝试通过JavaScript处理所有事情。)

The program works except for a problem with sessionStorage.

(该程序可以正常工作,除了sessionStorage的问题。)

The error I am getting is that the username always displays as the username in the active browser.

(我收到的错误是用户名始终在活动浏览器中显示为用户名。)

For example, if there are two users in a room, User1 and User2, all messages on User1's screen will display as from User1, even those sent from User2.

(例如,如果一个房间中有两个用户,即User1和User2,则User1屏幕上的所有消息都将显示为User1,甚至包括User2发送的消息。)

On User2's screen all message show as from User2.

(在User2的屏幕上,所有消息均显示为来自User2。)

Here is the code handling the chat window:

(这是处理聊天窗口的代码:)

// Declare variables
    var userName;
    document.getElementById("chatname").innerHTML = roomName;

// Set User
    window.onload = function(){
        userName = sessionStorage.getItem("user");
        if (userName==null || userName===false) {
            userName = prompt("Please enter a username:");
        };
        return userName;
    }


// Create Websocket
    var chatSocket = new ReconnectingWebSocket(
        'ws://' + window.location.host +
        '/ws/chat/' + roomName + '/');

// Send message
    chatSocket.onmessage = function(e) {
        var data = JSON.parse(e.data);
        var message = data['message'];
        var currentDate = new Date();
        var currentTime = currentDate.toLocaleTimeString();
        document.querySelector('#chat-log').value += (userName + " " + currentTime + ': ' + message + '
');
        document.getElementById("chat-log").scrollTop = document.getElementById("chat-log").scrollHeight;
    };

    chatSocket.onclose = function(e) {
        console.error('Chat socket closed unexpectedly');
    };

    document.querySelector('#chat-message-input').focus();
    document.querySelector('#chat-message-input').onkeyup = function(e) {
        if (e.keyCode === 13) {  // enter, return
            document.querySelector('#chat-message-submit').click();
        }
    };

    document.querySelector('#chat-message-submit').onclick = function(e) {
        var messageInputDom = document.querySelector('#chat-message-input');
        var message = messageInputDom.value;
        chatSocket.send(JSON.stringify({
            'message': message
        }));

        messageInputDom.value = '';
    };

The strange thing about this error is that the code does work for timestamps, which are set at the correct time and not differing by user.

(关于此错误的奇怪之处在于,代码确实适用于时间戳,这些时间戳是在正确的时间设置的,并且用户之间没有区别。)

The issue must be that the message content is being overwritten with the userName var some time after submission and yet the timestamps are persistent and correct.

(问题必须是消息内容在提交后的某个时间被userName var覆盖,但是时间戳是持久且正确的。)

Maybe the issue is caused by setting the userName in onload, maybe I could use a different event to set the userName?

(也许是由于在onload中设置userName引起的,也许我可以使用其他事件来设置userName?)

I could set the username outside of the context of the page itself, like in the consumer.py and that might resolve the issue?

(我可以在页面本身的上下文之外设置用户名,例如在consumer.py中,这样可以解决问题?)

Here is the consumer.py:

(这是consumer.py:)

from channels.generic.websocket import AsyncWebsocketConsumer

import json

class ChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'chat_%s' % self.room_name

        # Join room group
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )

        await self.accept()

    async def disconnect(self, close_code):
        # Leave room group
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    # Receive message from WebSocket
    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        # Send message to room group
        await self.channel_layer.group_send(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message
            }
        )

    # Receive message from room group
    async def chat_message(self, event):
        message = event['message']

        # Send message to WebSocket
        await self.send(text_data=json.dumps({
            'message': message
        }))

  ask by botasbot translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...