The Java WebSocket specification also defines a programmatic Java interface for connections. Without annotation, a POJO has to extend the abstract class
javax.websocket.Endpoint
and write the implementation methods: onOpen()
, onClose()
and onError()
.
Here is an implementation of the echo WebSocket from earlier:
public class EchoProgramServerEndpoint extends Endpoint { public void onOpen( final Session session, EndpointConfig config) { session.addMessageHandler( new MessageHandler.Whole<String>() { @Override public void onMessage(String message) { System.out.printf( "Received message=%s ", message); try { session.getRemoteBasic() .sendText("ECHO "+message); } catch (Exception e) { } } }); } public void onClose(Session session, CloseReason closeReason) { /* ... */ } public void onError(Session session, Throwable throwable) { /* ... */ } }
In the onOpen()
method inside the EchoProgramServerEndpoint
, we register a MessageHandler
in order to receive messages from remote peers. A
MessageHandler
has two sub interfaces: Whole
or Partial
. The
Whole
interface is designed for applications that want to consume entire messages as they arrive. The Partial
interface is designed for applications that consume partial messages.
The anonymous message handler in EchoProgramServerEndpoint
accepts a String text message from the remote peer. It then sends the echo message back to the peer with the captured Session
instance from the onOpen
method parameter.
3.135.187.210