gpt4 book ai didi

JavaScript WebSocket 尝试打开...然后关闭,没有错误

转载 作者:行者123 更新时间:2023-11-28 02:12:45 25 4
gpt4 key购买 nike

我正在尝试验证 WebSockets HTML5 和 JavaScript 的工作原理。我没有看到任何错误,但似乎只是挂起一会儿,然后调用关闭的回调。不确定我做错了什么,但我认为 onopen 回调函数会在这里被调用。

            var socket;

window.onload = function(argument) {

try
{

document.getElementById("console").innerHTML = "Opening WebSocket...";

socket = new WebSocket("ws://undergroundtechnetwork.com:8080/");

socket.onopen = function(){
document.getElementById("console").innerHTML += "<br />WebSocket opened.";
}

socket.onmessage = function(message){
document.getElementById("console").innerHTML += "<br />WebSocket recieved a message: " + message;
}

socket.onclose = function(){

document.getElementById("console").innerHTML += "<br />WebSocket status: " + GetSocketStateName(socket.readyState);
}

socket.onerror = function(e){
document.getElementById("console").innerHTML += "<br />WebSocket error message:<br />" + JSON.stringify(e);
}


}catch(e){
document.getElementById("console").innerHTML += "<br />Exception: " + e;
}

}

function GetSocketStateName(state){
var strSocketState;

if(socket.readyState == 0){
strSocketState = "Connecting";
}else if(socket.readyState == 1){
strSocketState = "Open";
}else if(socket.readyState == 2){
strSocketState = "Closing";
}else if(socket.readyState == 3){
strSocketState = "Closed";
}

return strSocketState;
}

更新:

这是我在错误中遇到的错误。我没有收到 8080 的错误,但那是因为它没有实际打开(它是托管服务服务器)

{"cancelBubble":false,"returnValue":true,"srcElement":{"binaryType":"blob","扩展名":"","协议(protocol)":"","bufferedAmount":0,"readyState":0,"url":"ws://undergroundtechnetwork.com/","URL":"ws://undergroundtechnetwork.com/"},"defaultPrevented":false,"timeStamp":1369930726244,"可取消":false,"bubbles":false,"eventPhase":2,"currentTarget":{"binaryType":"blob","扩展名":"","协议(protocol)":"","bufferedAmount":0,"ReadyState":0,"url":"ws://undergroundtechnetwork.com/","URL":"ws://undergroundtechnetwork.com/"},"target":{"binaryType":"blob","扩展名":"","协议(protocol)":"","bufferedAmount":0,"readyState":0,"url":"ws://undergroundtechnetwork.com/","URL":"ws://undergroundtechnetwork .com/"},"类型":"错误"}

最佳答案

你的 JavaScript 看起来没问题。如果你改变

socket = new WebSocket("ws://undergroundtechnetwork.com:8080/");

比方说

socket = new WebSocket("ws://echo.websocket.org");

效果很好。尝试调整您的 WebSocket 服务器。

关于JavaScript WebSocket 尝试打开...然后关闭,没有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16839608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com