WebSocket

org.apache.johnzon:johnzon-websocket:2.2.0

Contents

johnzon-websocket integrates Johnzon with the Java WebSocket API (JSR 356) at codec level (encoders/decoders). There are three codec families:

  • JSON-P based: JsonObject, JsonArray, JsonStructure
  • Mapper based: your POJOs through the Johnzon mapper
  • JSON-B based: your POJOs through JSON-B

Codecs

JSON-P encoders JsrObjectEncoder, JsrArrayEncoder, JsrStructureEncoder and decoders JsrObjectDecoder, JsrArrayDecoder, JsrStructureDecoder live in org.apache.johnzon.websocket.jsr.

Mapper codecs are org.apache.johnzon.websocket.mapper.JohnzonTextEncoder and JohnzonTextDecoder.

JSON-B codecs are org.apache.johnzon.websocket.jsonb.JsonbTextEncoder and JsonbTextDecoder.

To control the Mapper or Jsonb instance the decoders use, register the matching servlet listener: org.apache.johnzon.websocket.internal.mapper.MapperLocator for the mapper, org.apache.johnzon.websocket.jsonb.JsonbLocator for JSON-B. Alternatively, set a servlet context attribute named …MapperLocator.mapper (a Supplier<Mapper>) or …JsonbLocator.jsonb and it will be used instead of the default instance.

JSON-P endpoints

Server and client side, provide the codecs to @ServerEndpoint/@ClientEndpoint (or EndpointConfig with the programmatic API):

@ClientEndpoint(encoders = JsrObjectEncoder.class, decoders = JsrObjectDecoder.class)
public class JsrClientEndpointImpl {
    @OnMessage
    public void on(final JsonObject message) {
        // ...
    }
}

@ServerEndpoint(value = "/my-server", encoders = JsrObjectEncoder.class, decoders = JsrObjectDecoder.class)
public class JsrServerEndpointImpl {
    @OnMessage
    public void on(final JsonObject message) {
        // ...
    }
}

Mapper endpoints

Server configuration is as simple as providing the codecs to @ServerEndpoint:

@ServerEndpoint(value = "/server", encoders = JohnzonTextEncoder.class, decoders = JohnzonTextDecoder.class)
public class ServerEndpointImpl {
    @OnMessage
    public void on(final Session session, final Message message) {
        // ...
    }
}

On the client side Johnzon cannot guess the expected type, so provide it by extending JohnzonTextDecoder:

@ClientEndpoint(encoders = JohnzonTextEncoder.class, decoders = ClientEndpointImpl.MessageDecoder.class)
public class ClientEndpointImpl {
    @OnMessage
    public void on(final Message message) {
        // ...
    }

    public static class MessageDecoder extends JohnzonTextDecoder {
        public MessageDecoder() {
            super(Message.class);
        }
    }
}