03 January 2014

Java WebSocket Sample

I have not been updating this blog for some time but I was unsatisfied with my search on Java Websockets topic on the client implementation in Java and configuration so I decided to post one.

There is valuable info on several blogs and presentation slides on Java WebSockets, but generally the samples are about the implementation of server side and websocket client is implemented on html/JavaScript, I wanted a client implementation in Java.

I decided to provide a complete  sample, with  both a Java websocket server and java client together with the html/javascript one.

The sample application is a virtual USD Exchange rate publishing server and the websocket client consumes the new USD rate as it becomes available.

How to Configure:

1. For the server implementation: WebSockets standard is included in JEE7 so you app.server must be supporting JEE7.
WebSphere Liberty 8.5.5 did not run this so I went with GlasssFish 4.0 (build 89)

Just deploy the application as a war or ear file. Since annotation based approach is used no need to configure a web.xml/deployment descriptor.

2. For the Java client implementation: JSE7 does not include WebSockets so you should add necesessary jar files yourself. I used Tyrus as the websocket api implementation.

Use javax.websocket-api.jar and tyrus-standalone-client-1.3.3.jar from https://tyrus.java.net/

3. Java client should have a file named javax.websocket.ContainerProvider in MEFA-INF/services folder with the content org.glassfish.tyrus.client.ClientManager to introduce Tyrus to JSE7 environment as WebSocketContainer provider . (see ServiceLoader API for details)

4. For the html/javascript implementation: IE9 does not support websockets,IE version must be at least 10.
For Firefox and Chrome...they have been supporting websockets for a very long time so it won't be a problem.
see caniuse.com for more info on browser support.

Here is the server application

package websocket.server;

import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.*;
import javax.websocket.*;
import javax.websocket.server.*;

public class CustomEndPoint {
private static Queue<Session> queue = new ConcurrentLinkedQueue<Session>();
private static Thread rateThread ;

{//rate publisher thread, generates a new value for USD rate every 2 seconds.
rateThread=new Thread(){
public void run() {
DecimalFormat df = new DecimalFormat("#.####");
double d=2+Math.random();
sendAll("USD Rate: "+df.format(d));
try {
} catch (InterruptedException e) {
} ;

public void onMessage(Session session, String msg) {
try {
System.out.println("received msg "+msg+" from "+session.getId());
} catch (Exception e) {

public void open(Session session) {
System.out.println("New session opened: "+session.getId());

public void error(Session session, Throwable t) {
System.err.println("Error on session "+session.getId());

public void closedConnection(Session session) {
System.out.println("session closed: "+session.getId());

private static void sendAll(String msg) {
try {
/* Send updates to all open WebSocket sessions */
ArrayList<Session > closedSessions= new ArrayList<>();
for (Session session : queue) {
System.err.println("Closed session: "+session.getId());
System.out.println("Sending "+msg+" to "+queue.size()+" clients");
} catch (Throwable e) {

and here is the Java WebSocket Client:

public class WSClient  {

  private static Object waitLock = new Object();

    public void onMessage(String message) {
       System.out.println("Received msg: "+message);        

    public void onOpen(Session p) {
        try {
            p.getBasicRemote().sendText("Session established");           
        } catch (Exception e) {

private static void  wait4TerminateSignal()
try {
} catch (InterruptedException e) {

    public static void main(String[] args) {
    WebSocketContainer container=null;
    Session session=null;
container = ContainerProvider.getWebSocketContainer();
//WS1 is the context-root of my web.app 
//ratesrv is the path given in the ServerEndPoint annotation on server implementation
session=container.connectToServer(WSClient.class, URI.create("ws://localhost:8080/WS1/ratesrv"));
} catch (Exception e) {
try {
} catch (IOException e) {

The html/javascript client is:

<!DOCTYPE html>
<meta charset="UTF-8">
<title>WebSocket Client</title>
 <script type="text/javascript">

      var wsocket;
      function connect() {        
          wsocket = new WebSocket("ws://localhost:8080/WS1/ratesrv");        
          wsocket.onmessage = onMessage;          
      function onMessage(evt) {             
      window.addEventListener("load", connect, false);

<td> <label id="rateLbl">Current Rate:</label></td>
<td> <label id="rate">0</label></td>

I hope this helps


Jean-Michel David said...


thank you for sharing this. Do you know how to connect to a WebSocket with Spring Security?


Anonymous said...

Your way of explaining the whole thing in this paragraph is actually good, all be capable of without difficulty understand it,
Thanks a lot.

Here is my site goji berry

Anonymous said...

You actually make it seem so easy with your presentation but I find
this topic to be really something which I think
I would never understand. It seems too complicated and very broad for me.
I'm looking forward for your next post, I will try to get the
hang of it!

Visit my blog post pillow humping

Anonymous said...

This is a topic which is near to my heart...

Many thanks! Where are your contact details

Look into my page - Evansville roofing contractors

Murat Döner said...

I get some errors with this configuration about "not a subtype".

I write into Client Project's META-INF/Services/javax.websocket.ContainerProvider:

And it is working now.