Django Channels websocket.recieve发送空字符串Python

时间:2019-04-27 19:13:00

标签: python django django-views django-channels

我终于使用Django Channels 2.1.2使Websocket工作了。

用户提交邮件时,该邮件与另一个空白实例一起提交。用户发送的消息越多,发送的空白实例也就越多(它们建立起来,并且使其停止发生的唯一方法是对页面进行CNTRL-R硬刷新)。

这是它的样子

127.0.0.1:54917 - - [27/Apr/2019:19:04:05] "WSCONNECTING /messages/trilla" - -
connected {'type': 'websocket.connect'}
127.0.0.1:54917 - - [27/Apr/2019:19:04:05] "WSCONNECT /messages/trilla" - -
receive {'type': 'websocket.receive', 'text': '{"message":"hi there"}'}
websocket.receive
receive {'type': 'websocket.receive', 'text': '{"message":""}'}
websocket.receive
receive {'type': 'websocket.receive', 'text': '{"message":""}'}
websocket.receive
receive {'type': 'websocket.receive', 'text': '{"message":""}'}
websocket.receive

我是一个初学者,所以这很明显。

我还试图让notification_id(来自我的Notification模型的一个字段)沿每条消息追加,但到目前为止,还没有运气。

我假设notification_id应该在Notification模型中定义为每次发送消息时都会创建的新对象?

consumers.py

class ChatConsumer(AsyncConsumer):
    async def websocket_connect(self, event):
        print('connected', event)

        other_user = self.scope['url_route']['kwargs']['username']
        me = self.scope['user']
        thread_obj = await self.get_thread(me, other_user)
        self.thread_obj = thread_obj
        chat_room = f"thread_{thread_obj.id}"
        self.chat_room = chat_room
        # below creates the chatroom
        await self.channel_layer.group_add(
            chat_room,
            self.channel_name
        )

        await self.send({
            "type": "websocket.accept"
        })


    async def websocket_receive(self, event):
        # when a message is recieved from the websocket
        print("receive", event)

        message_type = event.get('type', None)  #check message type, act accordingly
        print(message_type)
        if message_type == "notification_read":
            # Update the notification read status flag in Notification model.
            notification = Notification.object.get(id=notification_id)
            notification.notification_read = True
            notification.save()  #commit to DB
            print("notification read")

        front_text = event.get('text', None)
        if front_text is not None:
            loaded_dict_data = json.loads(front_text)
            msg =  loaded_dict_data.get('message')
            user = self.scope['user']
            username = 'default'
            notification_id = '??'
            if user.is_authenticated:
                username = user.username
            myResponse = {
                'message': msg,
                'username': username,
                'notification': notification_id,
            }
            await self.create_chat_message(user, msg)

            # broadcasts the message event to be sent, the group send layer
            # triggers the chat_message function for all of the group (chat_room)
            await self.channel_layer.group_send(
                self.chat_room,
                {
                    'type': 'chat_message',
                    'text': json.dumps(myResponse)
                }
            )
    # chat_method is a custom method name that we made
    async def chat_message(self, event):
        # sends the actual message
        await self.send({
                'type': 'websocket.send',
                'text': event['text']
        })

    async def websocket_disconnect(self, event):
        # when the socket disconnects
        print('disconnected', event)

    @database_sync_to_async
    def get_thread(self, user, other_username):
        return Thread.objects.get_or_new(user, other_username)[0]

    @database_sync_to_async
    def create_chat_message(self, me, msg):
        thread_obj = self.thread_obj
        return ChatMessage.objects.create(thread=thread_obj, user=me, message=msg)

base.html

<script>
    $(document).ready(function() {
      $("#notificationLink").click(function() {
        var data = {
          "type": "notification_read",
          "username": username,
          "notification_id": notification_id,
        }
        socket.send(JSON.stringify(data));
    $("#notificationContainer").fadeToggle(300);
    $("#notification_id").fadeOut("slow");
    return false;
  });

  //Document Click hiding the popup
  $(document).click(function() {
    $("#notificationContainer").hide();
  });

  //Popup on click
  $("#notificationContainer").click(function() {
    return false;
  });

});

<script>
    // websocket scripts - client side*
    var loc = window.location
    var formData = $("#form")
    var msgInput = $("#id_message")
    var chatHolder = $('#chat-items')
    var me = $('#myUsername').val()
    var notification = $("#notificationLink")

    var wsStart = 'ws://'
    if (loc.protocol == 'https:') {
      wsStart = 'wss://'
    }
    var endpoint = wsStart + loc.host + loc.pathname
    var socket = new ReconnectingWebSocket(endpoint)

    // below is the message I am receiving
    socket.onmessage = function(e) {
      var data = JSON.parse(event.data);
      // Find the notification icon/button/whatever and show a red dot, add the notification_id to element as id or data attribute.
      notification.append("<span id=#notification_id>" + notification.notification_id)

      console.log("message", e)
      var chatDataMsg = JSON.parse(e.data)
      chatHolder.append('<li>' + chatDataMsg.message + ' from ' + chatDataMsg.username + '</li>')
    }

    // below is the message I am sending
    socket.onopen = function(e) {
      console.log("open", e)
      formData.submit(function(event) {
        event.preventDefault()
        var msgText = msgInput.val()
        var finalData = {
          'message': msgText
        }
        socket.send(JSON.stringify(finalData))
        formData[0].reset()
      })
    }
    socket.onerror = function(e) {
      console.log("error", e)
    }
    socket.onclose = function(e) {
      console.log("close", e)
    }
  </script>

0 个答案:

没有答案