javascript - WebSocket Javascript 客户端未从服务器接收消息

标签 javascript java websocket

我在本地 GlassFish 4.1 服务器上部署了一个 Java Web 应用程序,该服务器实现了 WebSockets 以与 Web 客户端进行交互操作。我能够通过套接字成功执行客户端到服务器的通信,但服务器到客户端的通信由于某种原因不起作用。

向客户端发送消息的Java代码:

try 
{
    String msg = ServerClientInteropManager.toResponseJSON(response);
    parentSession.getBasicRemote().sendText(msg);
    FLAIRLogger.get().info("Sent response to client. Message: " + msg);
}
catch (IOException ex) {
    FLAIRLogger.get().error("Couldn't send message to session " + parentSession.getid() + ". Exception - " + ex.getMessage());
}

Javascript 代码:

pipeline_internal_onMessage = function(event)
{
    var msg = JSON.parse(event.data);
    console.log("Received message from server. Data: " + event.data);
};

function pipeline_init()
{
    if (PIPELINE !== null || PIPELINE_CONNECTED === true)
    {
        console.log("Pipline already initialized");
        return false;
    }
    else 
    {
        var pipelineURI = "ws://" + document.location.host + document.location.pathname + "webranker";
        console.log("Attempting to establish connection with WebSocket @ " + pipelineURI);

        if ('WebSocket' in window)
            PIPELINE = new WebSocket(pipelineURI);
        else if ('MozWebSocket' in window)
            PIPELINE = new MozWebSocket(pipelineURI);
        else
        {
            console.log("FATAL: No WebSockets support");
            alert("This browser does not support WebSockets. Please upgrade to a newer version or switch to a browser that supports WebSockets.");
            return false;
        }

        // the other event listeners get added here
        PIPELINE.onMessage = pipeline_internal_onMessage;
        PIPELINE_CONNECTED = true;

        window.onbeforeunload = function() {
            pipeline_deinit();  
        };

        console.log("Pipeline initialized");
        return true;
    }
}

即使服务器成功调用 sendText() 方法,onMessage 函数也永远不会被触发。使用 AsyncRemote 会产生相同的结果。两端的 onError 监听器也不会报告任何内容。这是我第一次使用套接字,所以我可能会错过一些基本的东西。

最佳答案

替换

PIPELINE.onMessage = pipeline_internal_onMessage

PIPELINE.onmessage = pipeline_internal_onMessage

请引用here了解更多。

关于javascript - WebSocket Javascript 客户端未从服务器接收消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35817613/

相关文章:

javascript - 从点计算可能的线

asp.net - 使用 JQuery 在 GridView ASP.NET 中选择所有复选框

python - 与 Flask-socketio 进行私有(private)聊天

java - javax.websocket.Session api

javascript - 使用node-http-proxy在同一子域下代理 Node 服务器和websocket服务器

javascript - 使用 javascript 的正则表达式将多个数字返回到数组中

javascript - 使用模板文字转换表达式

java - 集成 JPA 和 PostgreSQL 空列

java - jQuery Ajax 错误解决

java - php加密脚本需要类似的java代码