Java Magazine, Jan/Feb 2016
String String String String FooDecoder Foo ORACLE COM JAVAMAGAZINE JANUARY FEBRUARY 2016 48 web apps endpoint a WebSocket Decoder implementation which the runtime uses to convert the incoming message into an instance of the custom object type To handle custom objects in your send methods you must provide a Web Socket Encoder implementation that the runtime will use to convert instances of the custom object into a native WebSocket message We can summarize this kind of scheme in Figure 1 Figure 1 shows endpoints exchanging strings with the client at the top and other endpoints using an encoder and a decoder for converting Foo objects into WebSocket text messages and vice versa There is a family of javax websocket Decoder and javax websocket Encoder interfaces in the Java Web Socket API to choose from depending on what kind of conversion you wish to make For example to implement a Decoder that converts text messages into instances of a custom developer class called Foo you would implement the interface Decoder Text T using Foo as the generic type which would require you to implement this method public void sendObject Object message throwsIOException EncodeException This is the workhorse method of the decoder and would be called each time a new text message came in to produce an instance of the Foo class The runtime would then be able to pass this class into the message handling method of your endpoint There are sibling Decoder classes for decoding binary WebSocket messages and WebSocket messages that arrive in the form of a blocking I O stream which is also supported To implement an Encoder that converts instances of a custom developer class Foo into a WebSocket text message you would implement the Encoder Text T interface using Foo as the generic type This would require you to implement this method public String encode Foo foo throws EncodeException This does the work of converting Foo instances into strings which are needed by the Java WebSocket runtime if you call the RemoteEndpoints sendObject method discussed previously passing in an instance of the class Foo Like Decoders there are Encoder siblings for converting custom objects into binary messages and for writing custom objects to blocking I O streams in order to send the message This scheme is easy to wire into an endpoint if you want to use it as we saw in the definitions for @ ClientEndpoint and @ ServerEndpoint You can simply list the decoder and encoder implementations you want the endpoint to use in the decoders and encoders attributes respectively If you configure your own encoders or decoders for the Java primitive types they will override the runtimes default encoders or decoders for those types just as you would expect Figure 1 Encoders and decoders String String Endpoint Web Container RemoteEndpoint Foo Endpoint RemoteEndpoint FooEncoder Client Client
You must have JavaScript enabled to view digital editions.