1

我正在尝试检查 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"}

4

1 回答 1

1

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

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

比方说

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

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

于 2013-05-30T15:25:45.920 回答