I was taking a look at WebSockets last week and made a few thoughts on how to implement the server side with the Java Servlet API. I didn't spend too much time, but ran into the following problems during a few tests with Tomcat, which seem impossible to solve without patching the container or at least making container specific modifications to the HttpServletResponse implementation:
The WebSocket specification mandate a defined message in the 101 HTTP response. HttpServletResponse.setStatus(int code, String message) is deprecated without mentioning a usable replacement. After changing the default Tomcat configuration, I made Tomcat honor my message string, but since the method is deprecated, I'm not sure if this will work with other servlet containers.
The WebSocket specification require a specified order of the first few headers in the HTTP response to the connection upgrade request. The servlet API does not offer a method to specify the order of the response headers and Tomcat adds its own headers to the response, placing a few of them before any headers, which are added by the servlet implementation.
Since the content length of the response is not known when committing the header, Tomcat automatically switches to chunked transfer encoding for the response, which is incompatible with the WebSocket specification.
Am I missing something obvious, or is it really not possible to integrate WebSocket server endpoints in a servlet based web app?
A web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access-rights. A web container handles requests to servlets, Jakarta Server Pages (JSP) files, and other types of files that include server-side code.
Although its flexible configuration and interoperability with supporting technologies have enabled Apache Tomcat to act as a web application server in many circumstances, Tomcat is primarily a Java servlet container.
Apache Tomcat (called "Tomcat" for short) is a free and open-source implementation of the Jakarta Servlet, Jakarta Expression Language, and WebSocket technologies. It provides a "pure Java" HTTP web server environment in which Java code can also run.
There is an implementation in Jetty. We can hope that tomcat and jetty find a compatible API.
The Glassfish Atmosphere project will do what you want. There is a servlet you can define to do all the work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With