Tomcat 8 and Websocket

2019-08-04 13:16发布

i've troubles getting my application to tomcat 8. I'm using websocket and spring 4 but i don't want to use the spring internal STOMP mechanism so i've decided to follow this tutorial and implemented my websocket routines my way. I'm developing since a couple of weeks now and tested it always with jetty (maven jetty plugin) and everything works fine. But now i want to deploy my application to our production server running tomcat 8.0.15 on java 8 and CentOS but it's not working.

Here is the sourcecode:

@WebListener
public class MyApplication implements ServletContextListener {

private final static String SERVER_CONTAINER_ATTRIBUTE = "javax.websocket.server.ServerContainer";

@Override
public void contextInitialized(ServletContextEvent sce) {

    ServletContext container = sce.getServletContext();

    final ServerContainer serverContainer = (ServerContainer) container.getAttribute(SERVER_CONTAINER_ATTRIBUTE);
    try {
        serverContainer.addEndpoint(new MyEndpointConfig(MyEndpoint.class, "/wstest"));
    } catch (DeploymentException e) {
        e.printStackTrace();
    }
}
}

And here's the error:

java.lang.ClassCastException: org.apache.tomcat.websocket.server.WsServerContainer cannot be cast to javax.websocket.server.ServerContainer
at my.package.contextInitialized(MyApplication.java:23)

Line 23 is where i do the cast to ServerContainer. I guess that "container.getAttribute(SERVER_CONTAINER_ATTRIBUTE)" returns null and therefore the cast fails, but why??

It's all working fine with Jetty 9.2.3. I've tested it also with a local tomcat 8 installed (newest 8.0.18) and the latest JDK 8 on Windows 7 and same behaviour.

Do you have any ideas how to fix this?

Thank you very very much!

1条回答
闹够了就滚
2楼-- · 2019-08-04 13:39

Appleman1234 is pointing to a very useful bug report. See Iyad Elian comment:

FYI, I found why the exception happens javax.websocket-api like javax.servlet-api needs to be excluded at runtime in tomcat. jetty prefers application classloader to it's own however so it's not a problem.

<dependency>
    <groupId>javax.websocket</groupId>
    <artifactId>javax.websocket-api</artifactId>
    <version>1.0</version>
    <scope>provided</scope>
</dependency>

And that's exactly why it was not working on tomcat but on jetty. I've just added

<scope>provided</scope>

and now it's working fine. Thanks to Appleman1234!

查看更多
登录 后发表回答