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;

 
@ServerEndpoint("/hello")
public class HelloWorldEndpoint {

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

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

    @OnClose
    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:

modules\system\layers\base\javax\websocket\api\main\jboss-websocket-api_1.0_spec-1.0.0.Final.jar				

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:

 <dependencies>
        <dependency>

             <groupId>org.jboss.spec.javax.websocket</groupId>
             <artifactId>jboss-websocket-api_1.0_spec</artifactId>
             <version>1.0.0.Final</version>
        </dependency>

</dependencies>

0
0
0
s2smodern