Apache Tomcat 使用 websocket 时返回 404

Apache Tomcat returning 404 when using websocket

我在 AWS Elastic Beanstalk 上使用 Apache Tomcat/8.0.47,当我在本地 运行 上 mac 时,我可以正常连接并得到良好的响应:

curl --include \
     --no-buffer \
     --header "Connection: Upgrade" \
     --header "Upgrade: websocket" \
     --header "Host: example.com:80" \
     --header "Origin: http://example.com:80" \
     --header "Sec-WebSocket-Key: SGVsbG8sIHdvcmxkIQ==" \
     --header "Sec-WebSocket-Version: 13" http://localhost:8080/echo

但是如果我通过 ssh 进入 AWS 实例,我只会收到 404。

这不是 nginx 问题,因为我 运行在 ssh 进入时直接针对 Tomcat 端口

我花了一天时间四处寻找解决方案,但不知所措。我在网上找到的任何内容似乎都在尝试解决负载 balancer/nginx 问题。

我的代码供参考:

package com.mypackage.sockets

import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint(value = "/echo", configurator=EchoEndpointConfigurator.class)
public class EchoServer {

    private Set<Session> userSessions = Collections.synchronizedSet(new HashSet<Session>());

    @OnOpen
    public void onOpen(Session session) {
        System.out.println(session.getId() + " has opened a connection");
        userSessions.add(session);
    }

    @OnClose
    public void onClose(Session session) {
        System.out.println("Session " + session.getId() + " has ended");
        userSessions.remove(session);
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("Message from " + session.getId() + ": " + message);
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

}

package com.mypackage.sockets;

import javax.websocket.server.ServerEndpointConfig.Configurator;

public class EchoEndpointConfigurator extends Configurator {

    private static EchoServer echoServer = new EchoServer();

    @Override
    public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {
        return (T)echoServer;
    }
}

我也有一个 web.xml 文件,但它只引用了所有工作正常的 servlet

我可能需要在 AWS Elastic Beanstalk 上设置 Tomcat 的一些标志

事实证明,尽管 curl 命令在本地而不是远程工作,但这不是我的问题。通过直接在 ec2 上公开该端口,我能够弄清楚它正在端口 8080 上工作。最后,为了让它在端口 80 上工作,我从 Apache HTTPD 更改为 Nginx。然后使用经典的 Load Balancer 完美地工作。还没有弄清楚应用程序 Load-Balancer。