Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebSockets served by a Servlet Container

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?

like image 375
jarnbjo Avatar asked Feb 03 '10 08:02

jarnbjo


People also ask

What is Web container in Java servlet?

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.

Is Tomcat a servlet container?

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.

What is Tomcat in simple words?

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.


2 Answers

There is an implementation in Jetty. We can hope that tomcat and jetty find a compatible API.

like image 193
Horcrux7 Avatar answered Oct 07 '22 14:10

Horcrux7


The Glassfish Atmosphere project will do what you want. There is a servlet you can define to do all the work.

like image 21
dlaidlaw Avatar answered Oct 07 '22 15:10

dlaidlaw