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

时间:2013-05-30 15:02:47

标签: javascript websocket

我正试图审查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”:假 “的returnValue”:真 “srcElement”:{ “binaryType”: “斑点”, “扩展”: “”, “协议”: “”, “bufferedAmount”:0,” readyState的 “:0,” URL “:” WS://undergroundtechnetwork.com/ “ ”URL“: ”WS://undergroundtechnetwork.com/“}, ”defaultPrevented“:假的, ”时间戳“:1369930726244,” 取消“:假,” 泡沫 “:假” 的EventPhase “:2”,currentTarget当前 “:{” binaryType “:” 斑点 “ ”扩展“: ”“, ”协议“: ”“, ”bufferedAmount“:0,” readyState的 “:0,” URL “:” WS://undergroundtechnetwork.com/ “ ”URL“: ”WS://undergroundtechnetwork.com/“}, ”目标“:{ ”binaryType“: ”斑点“,”扩展名 “:” “ ”协议“: ”“, ”bufferedAmount“:0 ”readyState的“:0, ”URL“: ”WS://undergroundtechnetwork.com/“, ”URL“:” WS:// undergroundtechnetwork的.com / “},” 类型 “:” 错误“}

1 个答案:

答案 0 :(得分:1)

您的JavaScript似乎没问题。如果你改变了

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

让我们说

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

它工作正常。请尝试调整WebSocket服务器。