java-ee Creating a WebSocket communication


Example

WebSocket provides a duplex/bidirectional communication protocol over a single TCP connection.

  • the client opens a connection to a server that is listening for a WebSocket request
  • a client connects to a server using a URI.
  • A server may listen to requests from multiple clients.

Server Endpoint

You can create a WebSocket server entpoint by just annotate a POJO with @ServerEndpoint. @OnMessage decorates a method that receives incoming messages. @OnOpen can be used to decorate a method to be called when a new connection from a peer is received. Similarly, a method annotated with @OnClose is called when a connection is closed.

@ServerEndpoint("/websocket")
public class WebSocketServerEndpoint
{

    @OnOpen
    public void open(Session session) {
     System.out.println("a client connected");
    }

    @OnClose
    public void close(Session session) {
     System.out.println("a client disconnected");
    }

    @OnMessage
    public void handleMessage(String message) {
        System.out.println("received a message from a websocket client! " + message);
    }

}

Client Enpoint

Similar to the server endpoint you can create a WebSocket client endpoint by annotate a POJO with @ClientEndpoint.

@ClientEndpoint
public class WebsocketClientEndpoint {

    Session userSession = null;
    
    // in our case i.e. "ws://localhost:8080/myApp/websocket"
    public WebsocketClientEndpoint(URI endpointURI) {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        container.connectToServer(this, endpointURI);
    }

    @OnOpen
    public void onOpen(Session userSession) {
        System.out.println("opening websocket");
        this.userSession = userSession;
    }

    @OnClose
    public void onClose(Session userSession, CloseReason reason) {
        System.out.println("closing websocket");
        this.userSession = null;
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("received message: "+ message);
    }

    public void sendMessage(String message) {
        System.out.println("sending message: "+ message);
        this.userSession.getAsyncRemote().sendText(message);
    }
}