Press "Enter" to skip to content

WebSocket example in Java

WebSocket is a communication protocol providing a bi-directional communication channel between client and server. It allows us to directly send a message to the clients whenever something changes on the server side and we want all clients to be notified. Let’s see the skeleton for a simple WebSocket example in Java.

Depending on which server you use to run the example, you might be required to add the WebSocket API library as dependency. I’m running it on JBoss 6.3, so I’ve added the following dependency in my pom.xml


Creating a WebSocket endpoint in Java is not rocket science, you simply have to create a new class and use the @ServerEndpoint annotation to specify the path and the @OnOpen, @OnClose and respectively the @OnClose annotations to specify which methods to be run when one of those events occur. So a very basic WebSocket example without any extra logic would look like this:

package net.gazsi.laszlo.sandbox;

import javax.websocket.CloseReason;  
import javax.websocket.OnClose;  
import javax.websocket.OnMessage;  
import javax.websocket.OnOpen;  
import javax.websocket.Session;  
import javax.websocket.server.ServerEndpoint;

public class ExampleWebSocket {

   public void onOpen(Session session) {

   public void onMessage(String message, Session session) {

   public void onClose(CloseReason closeReason, Session session) {

After wrapping git up in a WAR and deploying it on a server that supports WebSockets, you will be able to connect to it by using the ws://localhost:8080/{app_name}/websocket address. You’ll have to replace {app_name} with the context root you’ve defined and also pay attention to the protocol. If the client runs on http, you should connect with ws, but if it runs on https, you must use wss, otherwise it will fail to connect due to security reasons. offers a great tool to test your WebSocket implementation. Because I usually start developing the server side and only when it is done do I start with the JavaScript part, for me it is very useful, because I can be sure that my implementation on the backend is working fine.