This post briefly demonstrates how to develop and deploy (server and client) Websocket endpoints using the programmatic version of the Java Websocket API
To begin with…
extend the javax.websocket.Endpoint class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ProgrammaticEchoEnpoint extends Endpoint { | |
@Override | |
public void onOpen(Session session, EndpointConfig config) { | |
System.out.println("Peer " + session.getId() + " connected"); | |
session.addMessageHandler(new MessageHandler.Whole<String>() { | |
@Override | |
public void onMessage(String message) { | |
try { | |
session.getBasicRemote().sendText("Got message from " + session.getId() + "\n" + message); | |
} catch (IOException ex) { | |
} | |
} | |
}); | |
} | |
@Override | |
public void onClose(Session session, CloseReason closeReason) { | |
System.out.println("Peer " + session.getId() + " disconnected due to " + closeReason.getReasonPhrase()); | |
} | |
@Override | |
public void onError(Session session, Throwable error) { | |
System.out.println("Error communicating with peer " + session.getId() + ". Detail: "+ error.getMessage()); | |
} | |
} |
Let’s code the client endpoint as well (using the same set of APIs)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ProgrammaticEchoClient extends Endpoint { | |
@Override | |
public void onOpen(Session session, EndpointConfig config) { | |
System.out.println("Connected to server"); | |
} | |
//a message handler and other life cycle implementations have been skipped on purpose… | |
} |
.. and then
implement the ServerApplicationConfig interface
It is part of the javax.websocket.server package and can be overridden to implement custom logic for endpoint deployment (for both annotated as well as programmatic endpoints)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CustomServerAppConfigProvider implements ServerApplicationConfig { | |
@Override | |
public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> endpointClasses) { | |
Set<ServerEndpointConfig> result = new HashSet<>(); | |
for (Class epClass : endpointClasses) { | |
//need to ignore Client endpoint class | |
if (epClass.equals(ProgrammaticChatEndpoint.class)) { | |
ServerEndpointConfig sec = ServerEndpointConfig.Builder.create(epClass, "/letschat").build(); | |
result.add(sec); | |
} | |
} | |
return result; | |
} | |
@Override | |
public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scanned) { | |
return Collections.emptySet(); | |
} | |
} |
What about the client endpoint ?
If required, you can create a your own instance of ClientEndpointConfig and use it while initiating a connection to the websocket server endpoint
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer(); | |
ClientEndpointConfig config = ClientEndpointConfig.Builder.create().decoders(StockTickDecoder.class).build(); | |
Session session = webSocketContainer.connectToServer(StockTickerClient().class, config, | |
new URI("ws://hotstocks.com/ticker")); |
To be noted
- Both the client as well as server endpoint config objects are nothing but object (programmatic) equivalents of the elements (value, encoders, decoders, configurator etc.) of the @ServerEndpoint and @ClientEndpoint annotations
- Separate builder classes (ServerEndpointConfig.Builder and ClientEndpointConfig.Builder) were used to create server and client configuration instances respectively
- The creation of a ServerEndpointConfig instance is mandatory since server endpoints cannot be deployed without a URI. This is not the case with client endpoints though – all they do is connect to an existing server endpoint.
- The endpoint config (server & client) have the notion of a configurator which can be created and set via the respective builder methods.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CustomServerEndpointConfigurator extends ServerEndpointConfig.Configurator { | |
//.. details ommitted | |
} | |
ServerEndpointConfig sec = ServerEndpointConfig.Builder.create(ChatEndpoint.class, "/letschat") | |
.configurator(serverEndpointConfigurator) | |
.build(); | |
public class CustomClientEndpointConfigurator extends ClientEndpointConfig.Configurator { | |
//.. details ommitted | |
} | |
ClientEndpointConfig config = ClientEndpointConfig.Builder.create() | |
.configurator(clientEndpointConfigurator) | |
.build(); |
Stay tuned for some more Websocket related action in the near future
feel free to…
- read some of my previous Websocket related posts
- check out the eBook – Java WebSocket API Handbook
Cheers!
Pingback: Deploying WebSocket annotated & programmatic server endpoints together | Thinking in Java EE (at least trying to!)
Pingback: Configuring WebSocket server endpoints | Thinking in Java EE (at least trying to!)