Coding the WebSockets server endpoint

As far as the Server Endpoint is concerned you can use two different programming:

  • Annotation-driven: Using annotated POJOs, developers can interact with the WebSocket lifecycle events.
  • Interface-driven: Developers can implement the Endpoint interface and the methods that interact with the lifecycle events.

In our example we will use the Annotation-Driven approach so an endpoint that is accepting incoming WebSocket requests can be a POJO annotated with the @ServerEndpoint annotation. This annotation tells the container that the given class should be considered to be a WebSocket endpoint. The required value element specifies the path of the WebSocket endpoint.

package com.sample.websocket;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

public class HelloWorldEndpoint {

    public String hello(String message) {
        System.out.println("Received : "+ message);
        return message;

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

    public void myOnClose(CloseReason reason) {
        System.out.println("Closing a WebSocket due to " + reason.getReasonPhrase());

Note: additionally this example contains two other callback methods: one bearing the @OnOpen annotation which is triggered when the WebSocket connection is started (just like the Javascript counterpart) and receiving as parameter the Web Session and another one carrying the @OnClose annotation which is obviously triggered when the connection is closed.

That's all. In order to compile this simple WebSocket application you need the Websockets API which are currently part of the WildFly 8 distribution in:


For Maven users, all you need to include as dependency is the undertow-websockets-jsr artifact which needs the latest Wildfly 8 Webserver whose name is Undertow: