Java EE 7: Sending JSON Objects Over WebSockets

Java EE 7 and particularly JSR 356: Java API for WebSockets supports Encoders to serialize any custom object into WebSocket stream. With JSR 353: Java API for JSON Processing the conversion between JsonObject instances and streams is straightforward:


import java.io.IOException;
import java.io.Writer;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonWriter;
import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;

public class JsonEncoder implements Encoder.TextStream<JsonObject> {

    @Override
    public void init(EndpointConfig config) {}

    @Override
    public void encode(JsonObject payload, Writer writer) throws EncodeException, IOException {
        try (JsonWriter jsonWriter = Json.createWriter(writer)) {
            jsonWriter.writeObject(payload);
        }
    }

    @Override
    public void destroy() {}
}


The Encoder instance needs to be registered with the @ServerEndpoint annotation:


[...]
@ServerEndpoint(value = "/changes", encoders = {JsonEncoder.class})
public class ToDoChangeTracker {

    private Session session;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
    }

    @OnClose
    public void onClose() {
        this.session = null;
    }

    public void onToDoChange([...]) throws EncodeException {
        if (this.session != null && this.session.isOpen()) {
            try {

                JsonObject event = Json.createObjectBuilder().
                        add("name",[...]).
                        build();
                this.session.getBasicRemote().sendObject(event);

            } catch (IOException ex) {
                //we ignore this
            }
        }
    }

}

This example was taken from the 38th episode of the Effective Java EE Online Workshop. Sources are available from github.com/AdamBien/doit


NEW online workshop: WebStandards Igniter (online)

Airport MUC workshops: Java EE 8, Java 9: Bootstrap, Effective, Architectures, Single Page Apps, Progressive Web Apps, HTML 5, ES 6, CSS 3 and Microservices

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

Helpful, tx!
Questions:
Why new writer is created from parameter?
If use only parameter writer, do I need to close parameter writer?

Posted by david on March 22, 2016 at 01:18 PM CET #

Post a Comment:
  • HTML Syntax: NOT allowed
realworldpatterns.com
Online Workshops
...the last 150 posts
...the last 10 comments
License