我正在尝试检查 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","extensions":"","protocol":"","bufferedAmount":0,"readyState": 0,"url":"ws://undergroundtechnetwork.com/","URL":"ws://undergroundtechnetwork.com/"},"defaultPrevented":false,"timeStamp":1369930726244,"cancelable":false ,"bubbles":false,"eventPhase":2,"currentTarget":{"binaryType":"blob","extensions":"","protocol":"","bufferedAmount":0,"readyState": 0,"url":"ws://undergroundtechnetwork.com/","URL":"ws://undergroundtechnetwork.com/"},"target":{"binaryType":"blob","extensions":"","protocol":"","bufferedAmount":0,"readyState":0,"url":"ws://undergroundtechnetwork.com/", "URL":"ws://undergroundtechnetwork.com/"},"type":"error"}