Custom Text and Binary Payloads using WebSocket (TOTD #186)

Posted by arungupta on Oracle Blogs See other posts from Oracle Blogs or by arungupta
Published on Fri, 16 Nov 2012 07:00:00 +0000 Indexed on 2012/11/16 11:08 UTC
Read the original article Hit count: 224

Filed under:

TOTD #185 explained how to process text and binary payloads in a WebSocket endpoint. In summary, a text payload may be received as

public void receiveTextMessage(String message) {
    . . .
}

And binary payload may be received as:

public void recieveBinaryMessage(ByteBuffer message) {
    . . .
}

As you realize, both of these methods receive the text and binary data in raw format. However you may like to receive and send the data using a POJO. This marshaling and unmarshaling can be done in the method implementation but JSR 356 API provides a cleaner way. For encoding and decoding text payload into POJO, Decoder.Text (for inbound payload) and Encoder.Text (for outbound payload) interfaces need to be implemented.

A sample implementation below shows how text payload consisting of JSON structures can be encoded and decoded.
public class MyMessage implements Decoder.Text<MyMessage>, Encoder.Text<MyMessage> {
    private JsonObject jsonObject;

    @Override
    public MyMessage decode(String string) throws DecodeException {
        this.jsonObject = new JsonReader(new StringReader(string)).readObject();      
        return this;
    }

    @Override
    public boolean willDecode(String string) {
        return true;
    }

    @Override
    public String encode(MyMessage myMessage) throws EncodeException {
        return myMessage.jsonObject.toString();
    }

public JsonObject getObject() { return jsonObject; }
}
In this implementation, the decode method decodes incoming text payload to MyMessage, the encode method encodes MyMessage for the outgoing text payload, and the willDecode method returns true or false if the message can be decoded.

The encoder and decoder implementation classes need to be specified in the WebSocket endpoint as:
@WebSocketEndpoint(value="/endpoint",
encoders={MyMessage.class},
decoders={MyMessage.class}) public class MyEndpoint { public MyMessage receiveMessage(MyMessage message) { . . . } }
Notice the updated method signature where the application is working with MyMessage instead of the raw string.

Note that the encoder and decoder implementations just illustrate the point and provide no validation or exception handling. Similarly Encooder.Binary and Decoder.Binary interfaces need to be implemented for encoding and decoding binary payload.

Here are some references for you:
Subsequent blogs will discuss the following topics (not necessary in that order) ...
  • Error handling
  • Interface-driven WebSocket endpoint
  • Java client API
  • Client and Server configuration
  • Security
  • Subprotocols
  • Extensions
  • Other topics from the API

© Oracle Blogs or respective owner

Related posts about /General