Wednesday, December 6, 2017

WebSockets client-server example

Server-side:

annotate a POJO with javax.websocket.server.ServerEndpoint

A method annotated with javax.websocket.OnOpen will handle the creation of a javax.websocket.Session

Another method handles the reception of a message, it's annotated with javax.websocket.OnMessage


Client-side:

You have to extend javax.websocket.Endpoint
and override the method onOpen(Session session, EndpointConfig config), where you add to the Session a MessageHandler.Whole to implement a onMessage() . This Endpoint just handles the Message but not the session.

To create a session, connect to the Server: ContainerProvider.getWebSocketContainer().connectToServer(this.endpoint, new URI("ws://server:port/contextroot/serviceuri"))


Client and server are here

https://github.com/vernetto/JavaMonAmour/tree/master/pvabwebsocketsserver

https://github.com/vernetto/JavaMonAmour/tree/master/pvabwebsocketsclient


Here the explanation by the Great Adam Bien





No comments: