Custom Text and Binary Payloads using WebSocket (TOTD #186)
- by arungupta
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:
JSR 356:
Java API for WebSocket - Specification (Early
Draft) and Implementation
(already integrated in GlassFish
4 promoted builds)
TOTD
#183 - Getting Started with WebSocket in GlassFish
TOTD
#184 - Logging WebSocket Frames using Chrome Developer
Tools, Net-internals and Wireshark
TOTD
#185: Processing Text and Binary (Blob, ArrayBuffer,
ArrayBufferView) Payload in WebSocket
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