Java Reference
In-Depth Information
14.3.3. Decoders and encoders
The WebSocket interfaces you'll see later in this chapter will allow you to register decoders
and encoders. These are useful for converting incoming messages to Java objects and then
converting Java objects into another representation when sending a message. You don't
need to use the decoder/encoder functionality to implement a WebSocket endpoint. But un-
less you're processing just text messages with no structure or binary data, decoders and
encoders will be invaluable in separating message processing from message encoding.
Java API for JSON
Although it's beyond the scope of this section, encoders and decoders will most likely use
SR-353, which is part of Java EE 7. This API provides a simple interface for generating
and consuming JSON. The code examples for this topic make extensive use of this API.
Let's start by taking a look at decoders.
Decoders
A decoder is invoked prior to a message being handed off to your code. A decoder im-
plements one of the subinterfaces of javax.websocket.Decoder . There are several
different interfaces to choose from:
TextStream— Works on a stream ( java.io.Reader )
Text— Works on a Java String that is fully loaded into memory
BinaryStream— Processed using an InputStream
Binary— Loaded into a ByteBuffer prior to being parsed
Which interface is picked depends on the data type you're transmitting. If it's JSON, you'd
use either TextStream or Text . For binary data, such as an image, you'd choose Bin-
aryStream or Binary . The CommandMessage decoder is shown in the following list-
ing.
Search WWH ::




Custom Search