ServerEndpoint/WebSocket 对可以在本地 Tomcat 上运行,但不能在 Heroku 中运行

问题描述 投票:0回答:1

我有这个 Java WebSocket 应用程序这里。我构建服务器端点 URL 的代码是:

function constructWebSocket(endpoint, onMessageCallback) {

    const url = constructWebSocketUrl(endpoint);
    const socket = new WebSocket(url);

    socket.onopen = (event) => {
        console.log("onopen. Event: ", event);
    };

    socket.onmessage = onMessageCallback;
    socket.onclose = (event) => {
        console.log("onclose. Event: ", event);
    };

    socket.onerror = (event) => {
        console.log("onerror. Event: ", event);
    };

    return socket;
}

function constructWebSocketUrl(endpoint) {
    const host = document.location.host;
    const path = document.location.pathname;
    const protocol = document.location.protocol;
    
    if (protocol.startsWith("https")) {
        return `wss://${host}${path}${endpoint}`;
    } else if (protocol.startsWith("http")) {
        return `ws://${host}${path}${endpoint}`;
    } else {
        throw `Unknown protocol: ${protocol}.`;
    }
}

(该应用程序部署在 Heroku 上。)

当我在本地 Tomcat 上运行 Web 应用程序时,上面的代码片段返回有效的 WebSocket,但在 Heroku 上它会返回

404 Not Found
并关闭代码 1006。我在这里缺少什么?

javascript websocket endpoint
1个回答
0
投票

检查是否存在任何可能影响 WebSocket 连接的 Heroku 特定配置或限制。 Heroku 对 WebSocket 连接有一些限制,因此请确保您的应用程序符合 Heroku 的 WebSocket 支持指南。

确保不存在阻止建立 WebSocket 连接的跨域问题。如果您的 WebSocket 服务器托管在与 Web 应用程序不同的域或端口上,您可能需要配置 CORS(跨源资源共享)标头以允许来自 Web 应用程序的 WebSocket 连接。

© www.soinside.com 2019 - 2024. All rights reserved.