Django channels is auto disconnecting after sending message

95 views
Skip to first unread message

Sudipto Sarker

unread,
Jun 15, 2021, 8:28:02 AM6/15/21
to Django users
  I am working on a personal chat application in django using django channels. The problem is that after sending message from user1 to user2, the channels of user1(all connected channels) is auto disconnecting after sending message to chat room, although the message is passed successfully to user2 and appeared in screen. There is no particular error message. In console it shows,

HTTP GET /? 200 [0.22, 127.0.0.1:52178
WebSocket DISCONNECT /chat/3/ [127.0.0.1:58587]

I am using Memurai instead of redis because of windows. 
I am struggling with this problem since last 10-12 days but still not get any clue how to solve this. If code here is not visible properly here is the google drive link

version of packages:

Python 3.8.8 
channels 3.0.3
channels-redis 3.2.0 
Django 3.0

consumers.py:

class PersonalChatConsumer(WebsocketConsumer):
    def connect(self):
        print(" Connecting....")
        self.room_name = self.scope['url_route']['kwargs']['room_id'];
        self.room_group_name = 'chat_%s' % self.room_name

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

        self.accept()
        # print(self.scope['user'].id);
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
            'type': 'chat_join',
            'user_id': self.scope['user'].id,
            'username': self.scope['user'].username,
            }
        )

        print("Connected Successfully...")

    def chat_join(self, event):
        print("chat_join() called...")
        self.send(text_data=json.dumps({
          'msg_type': 'join',
          'user_id': event['user_id'],
          'username': event['username'],

        }))
    def disconnet(self, close_code):
        print("Disconneting...")

        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )
        print("Disconneted..")

    def receive(self, text_data):
        data = json.loads(text_data)
        print("message", data)
        print(data['content'])
        # The problem is caught here,  error is occurred which I added above and after that            page reloaded 
        # Whatever I added after the problem remains same.

I have tried WebSocketConsumer, AsyncWebSocketConsumer, AsyncJsonWebsocketConsumer but the problem remains same. It got stuck in receive() option and page reloaded.

chat.html: Only websocket part I added.

<!-- ********************************************************** -->
<script>
  let messageBody = document.getElementById("message-box");
  let contactProfile = document.getElementById('contact-profile');
  let otherUserImage = document.getElementById('other_user_or_group_image');
  let otherUserName = document.getElementById('chatroom-title');
  let messageInputBox = document.getElementById('message-sent-box');
  let chatLog = document.getElementById("chat_log");
  let scrollPos = 0;
  let previewBox = document.getElementById('previewBox');
  let previewImage = document.getElementById('preview-image');
  let activeStatus = document.getElementById('active-status');

   let chatSocket = null;
   let roomId = null;
   let requestUserId = null;
   let otherUserId = null;


   // --------- setupWebSocket -----------------------------
  function setupWebSocket(room_id, request_user_id, other_user_id){
    roomId = room_id;
    requestUserId = request_user_id;
    otherUserId = other_user_id;

    let isValidRoom = onSelectFriend(otherUserId);
    console.log(isValidRoom);

    if(isValidRoom){

      chatSocket = new WebSocket(
          'ws://'
          + window.location.host
          + '/chat/'
          + roomId
          + '/'
      );

      activeStatus.textContent = '';
      messageInputBox.classList.remove('d-none');

      chatSocket.onmessage = function(message){
        let data = JSON.parse(message.data);
        console.log("on load message");
        console.log(data);
        if(data.msg_type == 'join'){
           showActiveStatus(data);
        }
        if(data.msg_type == 'new_message'){
          // console.log()
        }
      }

    }


  }

// --------- ./setupWebSocket -----------------------------

//-------------- Active Status ----------------------------
function showActiveStatus(message){
   let userId = message.user_id;
   console.log(userId);

   if (userId !== requestUserId){
     activeStatus.textContent = ' Active';
   }
}

//-------------- Active Status ----------------------------

/* ------------- send Message ------------------- */

 // click the submit button
document.getElementById('chat-message-input').focus();
document.querySelector('#chat-message-input').onkeyup = function(e) {

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

send message to chatroom
document.querySelector('#chat-message-submit').onclick = function(e) {
    var messageInputDom = document.getElementById('chat-message-input');
    console.log("Input ");
    var message = messageInputDom.value;
    console.log(message);

    // console.log("target value" + e.target.value)
    console.log(chatSocket);
    chatSocket.send(JSON.stringify({
        'command': 'send_message',
        'message': message,
        'room_id': roomId,
        'type': 'message',
    }));
    messageInputDom.value = '';
};

/* ------------- ./send Message ------------------- */



//  getting or creating chat room
function onSelectFriend(otherUserId){


   // need to uncomment later
  // closePreviewBox();

  const csrf = document.getElementsByName('csrfmiddlewaretoken');

  payload = {
    "csrfmiddlewaretoken": csrf[0].value,
    "user_id": otherUserId,
  }

  $.ajax({
    type: 'POST',
    dataType: "json",
    url: "/get_or_create_chat_room/",
    data: payload,
    success: function(response){
      console.log(response);
      if(response.status == 'success'){

        contactProfile.classList.remove('d-none');
        otherUserImage.src = response.other_user_image_url;
        otherUserName.textContent = response.other_user_name;

      }
    },
    error: function(error){
       console.log(error);
       alert("Something went wrong.")

    },
  })

  if(otherUserImage.src != ''){
    return true;
  }
  else{
    return false;
  }
}

// end of get or creating chat room

</script>

<!-- ********************************************************** -->
Anybody here can help me to solve this? I am really struggling to solve this.  
Thanks in advance.

 

  
Reply all
Reply to author
Forward
0 new messages