Java Magazine, Jan/Feb 2016
ORACLE COM JAVAMAGAZINE JANUARY FEBRUARY 2016 57 web apps connections to broadcast the new chat message out to all the clients so that they can update their user interfaces with the latest chat message Notice that the message that is sent is in the form of a ChatMessage here the ChatUpdateMessage The ChatEncoder takes care of marshaling the ChatUpdateMessage instance into a text message that is actually the one sent back to the client with the news of the new chat message contained within Because we did not look at the ChatDecoder when we were looking at incoming messages lets pause to look at the ChatEncoder class as shown in Listing 7 Listing 7 The ChatEncoder class import java util Iterator import javax websocket EncodeException import javax websocket Encoder import javax websocket EndpointConfig public class ChatEncoder implements Encoder Text ChatMessage public static final String SEPARATOR @ Override public void init EndpointConfig config @ Override public void destroy @ Override public String encode ChatMessage cm throws EncodeException if cm instanceof StructuredMessage String dataString for Iterator itr StructuredMessage cm getList iterator itr hasNext dataString dataString SEPARATDR itr next return cm getType dataString else if cm instanceof BasicMessage return cm getType BasicMessage cm getData else throw new EncodeException cm Cannot encode messages of type cm getC1ass You can see that the ChatEncoder class is required to implement the Encoder lifecycle methods init and destroy Although this encoder does nothing with these callbacks from the container other encoders may choose to initialize and destroy expensive resources in these lifecycle methods The encode method is the meat of the class and takes the message instance and turns it into a string ready for transmission back to the client Returning now to the ChatServer class we see from the handleChatMessage method that this endpoint has a graceful way of dealing with clients that sign of in the proper way by sending a UserSignoffMessage prior to closing the connection It also has a graceful way of dealing with clients who simply close the connection unilaterally perhaps by closing the browser or navigating away from the page The @ OnClose annotated endChatChannel method broadcasts a message to all connected clients informing them The encode method is the meat of the class and turns the message instance into a string ready for transmission back to the client
You must have JavaScript enabled to view digital editions.