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

24 October 2010

Vor- Thief (1997)

This movie was nominated as the Best Foreign Language Movie in Oscar, European Film Awards, Golden Globe and many others, see the IMDB page for all list. It has a total o 7 awards in several organizations.

It is a nice and warm movie, Sanya's father is dead, they meet a soldier on a train with her mother, romance starts between the soldier and mother and they start to live together but it appears that he is not a real soldier but a thief!

I liked this one and highly recommend.IMDB

Voditel dlya Very -A Driver for Vera (2004)

This nice movie reminded me the Turkish movies of 60s, a young soldier is assigned as a driver for a Soviet Army General in 1962 in Sevastopol, Crimea, General's daughter is physically disabled and has a hard-spoilt personality but later a romance starts between these two...

Doesn't it remind you Ayhan Isik and Belgin Doruk concept:)

it was a nice movie, I can recommend this one to everybody.

4 (2005)

I did not understand much from this movie, this might be another sample representing that i am not an arts guy:) because it has several awards
see IMDB link

06 October 2010

Sorok Pervy -The Forty-First (1956)

During Russian Civil war, a Red Army unit captures an important white officer who is believed to carry important information from Kolcak to Denikin [both are white commanders].

The only female member of the team is a sniper who has shot 40 whites already but misses this 41th but takes him prisoner...after many events a romance occurs between this two..

DVD of this movie is also sold on amazon.com and more movie info is available on IMDB and wikipedia. I personally liked this idea.

15 September 2010


This Georgian comedy Mimino(means Falcon) is a nice watch, it is funny and warm. I would recommend it but I must say that it is not completely in Russian, some parts are in Georgian.
More info here.

05 September 2010

Little Moscow(2008)

Great! movie,I liked this one very much. Highly recommended!!

Mała Moskwa is set in the 1960s in the southwestern Polish city of Legnica, where Krzystek(the director of this movie) was born in 1953. Legnica was the headquarters of the Soviet forces stationed in Poland from 1945 until 1990 and much of the city was a Soviet enclave closed to outsiders, including Polish citizens, during this time. Yuri (Dmitry Ulyanov) is a young Russian pilot and failed astronaut posted to Legnica with his even younger wife Vera (Svetlana khodchenkova, judged best leading actress for her performance). Vera learns Polish and becomes fascinated with Polish music and poetry. She meets Polish officer and musician Michał (Lesław Żurek) at a Polish-Soviet “friendship song contest” which she wins. The story inexorably leads to tragedy as Vera desperately tries to stop herself from falling in love with Michał, equally desperately tries to hide her infatuation when this fails, and finally kills herself. The grave of the Russian woman on whose life Mała Moskwa is based still attracts visitors.http://www.foriegnmoviesddl.com/2009/04/maa-moskwa-little-moscow-2008-waldemar.html

04 September 2010

The Ascent (1977) - Voskhozhdeniye

Yet another famous Soviet Movie, The Ascent (Voskhozhdeniye ) is listed in the 20 Must See Films list of Russian Life magazine (20 Must See Russian Films of course :) )

Two soviet partisans separate from their group to go yo the nearest village and find some food but they are captured by the Germans, you can feel the cold and freezing snow ..one more time remember how wild and cruel is the war, especially the WWII.

BUT I must say that the movie is only average,it can be considered slow on today's basis.More info on this black and white movie is here.

Shadows of Forgotten Ancestors (1964)

Shadows of Forgotten Ancestors(Tini zabutykh predkiv) is another famous Soviet movie, but I personally did not enjoy it very much, maybe I did not get the implications or symbols. The movie has 8.1/10 on IMDB.
The only good thing about this movie is you can see the daily village life, clothes, music in the Carpathian region.

22 August 2010

Igla (1988)

This '88 Soviet Movie is in fact not very interesting, its only point is the main actor is Victor Tsoi and this makes this movie important, worth seeing.

For those who do not know him: He is one of the pioneers of Russian Rock with his group Kino during Perestroika years. You can watch his song "A star called sun"
I personally did not like his songs in the movie very much, but for some reasons I understand that Russians love him.

The wall above, people who know Moscow will easily recognize, is on Arbat Street, it is a memorial site for Victor Tsoi who died on a car accident at the age of 28.

I found the movie here.

edit:in the meantime I liked this Kino song very much : ЗВЕЗДА ПО ИМЕНИ СОЛНЦЕ