2

每当我尝试使用此 JS 代码连接到我计算机上的 WebSocket 服务器时,我都会收到错误消息:

$(document).ready(function () {
    var ws;
    try{
        if("WebSocket" in window){   
                ws = new WebSocket("ws://localhost:50002"); 
                socket.onopen = function(){  
                    $('#topbar').empty();
                    $('#topbar').append('<form id="test">');
                    $('#topbar').append('<input>');
                    $('#topbar').append('</form>');

                }  

                socket.onmessage = function(msg){  
                    ;  
                }  

                socket.onclose = function(){  
                    ;  
                } 

                socket.onerror = function(error){
                    $('#topbar').append('<div>Cannot make a connection with the server. Server is most likely in maintenance mode. Try again later</div>');
                }
        }
    }
    catch(exception) {$('#topbar').append('<div>Cannot make a connection with the server. Server is most likely in maintenance mode. Try again later</div>');}

});

我在 Firefox 中运行此代码,但是当我跟踪我的代码时,触发了 Catch 事件而不是 OnOpen,我收到以下消息:

[11:58:50.103] 到 ws://localhost:50002/ 的连接在页面加载时中断。@/lib/default.js:5

我知道这是 Firefox 中的一个错误,但我的服务器控制台一直说它已接受来自我的计算机 127.0.0.1 的连接。我错过了什么吗?我在 C# 中使用 Fleck 服务器

4

1 回答 1

1

虽然我无法为您的服务器问题提供答案,但在第 6 行,您立即调用了一个socket尚不存在的变量 ( ),并在整个脚本中继续使用该变量。这实际上至少会导致您catch被触发,因为它会产生异常。

socket替换with的实例ws(反之亦然),让我们看看它在哪里。

于 2013-10-11T23:05:20.027 回答