Websocket Connection Disconnects Quickly in JavaScript

Asked 2 years ago, Updated 2 years ago, 133 views

I would like to connect to the Websocket server via JavaScript, but the connection will be cut off as soon as I connect.If you look at the console, as soon as the page is loaded, you will see Open and close as shown below.Why does it disconnect so quickly?

console:


Open
Close

JavaScript


var post_button = document.getElementById("post");
varws=newWebSocket("ws://localhost:4283/chat");

function generateDOM(name, content){
    varbase_div = document.createElement("div");
    varp_content= document.createElement("p");
    varp_name = document.createElement("p");
    base_div.className="message-card";
    p_content.className="content";
    p_name.className="name";
    p_name.textContent=name;
    p_content.textContent=content;
    base_div.appendChild(p_name);
    base_div.appendChild(p_content);
    return base_div
}

post_button.onclick=function(e){
    ws.send(JSON.stringify({Name:name,Message:input_area.value});
};

ws.onopen=function(e){
    console.log("Open");
}

ws.onmessage=function(e){
    vard = JSON.parse(e.data.toString());
    vare=generateCard(d.name,d.message);
    c.appendChild(e);
}

ws.onclose=function(){
    console.log("Close");
}


javascript websocket

2022-09-30 10:30

1 Answers

Receive the CloseEvent in the Close Code or reason in the Close Code function.https://www.rfc-editor.org/rfc/rfc6455#section-7.1.6"rel="nofollow noreferrer">Close Reason) and you'll get some tips.

ws.onclose=function(e){
    console.log("Close Code="+e.code);
    console.log("Close Reason="+e.reason);
}


2022-09-30 10:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.