0

Hope you all are doing well. I am trying to create a chat inbox just like instagram, where I am stuck on a problem that the design has to be like in a way that it should display threads on left side of the screen and when clicked upon a specific thread, it's corresponding chat box to appear on the right side as can be seen in the screenshot

inbox.html

The problem with this approach is that on the client side I have made a function that calls data via a promise object whenever a thread is clicked it data is loaded, browser history is manipulated and a socket is initiated this what the javascript for it looks like

inbox.html

function click_thread(e){
    
    $("#Chatbox").empty()
    $(".ChatLabel").remove()
    div=document.createElement("div")
    h3=document.createElement("h3")
    div.className="ChatLabel"
    h3.innerText=this.children[0].children[0].children[0].innerText
    div.appendChild(h3)
    $("#Chatholder").prepend(div)
    console.log(this.children[0].children[0].children[0].innerText);
    var other_user= this.children[0].children[0].children[0].innerText
      
    window.history.pushState(`inbox/${other_user}`,other_user,`${other_user}`)

    fetch(`/inbox/${other_user}`).then(response => response.json())
    .then(data => {

        messages= data;
        last_message_retriever(messages);
        data.messages.reverse().forEach(add_message)
            })

// For Socket initiation
var loc=window.location
var wsStart="ws://"

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

var chatholder= $("#Chatbox")
var form=$("#form")
var msg_input=$("#chat_message")

// Whenever a socket receives message from server
socket.onmessage=function(e){
    console.log("message",e)
    var msg_rec=JSON.parse(e.data)
    console.log(msg_rec)
    add_received_message(msg_rec.message,msg_rec.username)
    }
//When soocket sends data to the the server 
socket.onopen=function(e){
    console.log("open",e)
    // sends the status of message
    $("#chat_message").on("click",function(e){
        socket.send(JSON.stringify({"status":"read",
            "msg":window.message}))
    })
    if($("#chat_message").length >0){
    form.submit(function(event){
        event.preventDefault()
        var msgtext=msg_input.val()
        var me =$("#myusername").val()
        data={
            "message":msgtext,
            'username':me
        }
        console.log(data)
        console.log("message",msgtext)
        socket.send(JSON.stringify(data))
        form[0].reset()

    })
    }};
socket.onerror=function(e){
    console.log("error",e)
}
socket.onclose=function(e){
    console.log("close",e)
            
}
};

The problem comes in this part whenever a user clicks on a thread for the second time, it initiates a socket object for the other user too, having two websockets open at the same time and when a message is sent to the server via submit button, both sockets send the message, the one that is intended to send the message will send it but the other unclosed connection will send an empty string to server, corrupting the database. Any help regarding this would be much appreciated.

0

1 Answer 1

1

If a socket is already open, close it.

if (socket.readyState === WebSocket.OPEN) {
    socket.close()
} 

Then connect to the new socket.

Sign up to request clarification or add additional context in comments.

3 Comments

Have already done that, it still doesn't close the websocket, have also tried storing the sockets in an array and popping out the first object, still didn't work
specially that socket.close() function isn't working
You are creating a new socket every time you execute your click_thread function. You should pass the previous socket into that function, check if it's open and if so, close it before creating a new one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.