This example shows about the simplest possible way to use web sockets (WS) between a web page and a Java web app.

The WS JavaScript API is defined in https://html.spec.whatwg.org/multipage/web-sockets.html, and the underlying network protocol in RFC:6455.

The war file can be downloaded here, ready for dropping into your servlet container's web apps directory. It contains the Java source code and an Ant build file. Once deployed, you can access the client page at http://localhost:8080/websocket

The Java source code consists of 3 files:

  • RequestListener.java
    • Intercepts an incoming request and ensures that an HTTP session is created
  • ServletAwareConfig.java
    • Stores a reference to the HTTP session in the user properties
  • SocketEndPoint.java
    • The actual WS endpoint, contained in the open, message, close and error methods. The message method reads the client message and generates the response from that.

Of these, only SocketEndPoint is really required for a basic setup. The others are scaffolding to allow access to the user session from which the servlet context can be obtained, used here for logging purposes. Generally, an HTTP session is not required, and should not be created unless necessary.


Server-Sent Events (SSE)

This example shows about the simplest possible way to use Server-Sent Events (SSE) between a web page and a Java web app. The SSE JavaScript API is defined in https://html.spec.whatwg.org/multipage/server-sent-events.html. Further documentation can be found at https://jersey.github.io/documentation/latest/sse.html (for the server-side using JAX-RS) and https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events (for the client side).

It's been tested with Tomcat 8.5 on Java 8 (which is the minimum Java version supported for JAX-RS 2.1). Note that the example in the documentation makes it seem as if the name of the message ("message-to-client") can contain hyphens - that does not work with current browsers. But that example code has in any case not been updated to the released version, so you're better off just using the source code that comes with this web app.

The war file can be downloaded here, ready for dropping into your servlet container's web apps directory. It contains the Java source code and an Ant build file. Once deployed, you can access the client page at http://localhost:8080/sse

The Java source code consists of 2 files:

  • SSE.java
    • A source of messages intended for sending to the client. In this case a thread creates a series of 10 messages over 10 seconds.
  • SSEBroadcaster.java
    • This class creates the actual events from the messages creates by SSE and sends them to the web page.


CodeSnippets