Java Reference
In-Depth Information
Listing 14.13.
ChatMessageHandler
used in ActionBazaar
The code shown in this listing implements the
MessageHandler.Whole
interface
to process complete messages. The constructor caches references to the
ChatServer
singleton bean along with the WebSocket session
. You use these cached entities when
you process the message
. There are a couple of things to remember when reading this
code sample:
• Each WebSocket connection gets its own instance of the
ChatMessageHand-
ler
.
• The
onMessage
takes a
ChatMessage
; WebSockets use a decoder,
ChatMessageDecoder
, to convert the JSON into a Java object.
In the next section you'll create endpoints and register the message handler.
Using programmatic WebSockets
Now that you have a message handler, it's time to define the endpoint. To define an end-
point, you must do four things:
1
. Define a class that extends
javax.websocket.Endpoint
.
2
. Provide an implementation of the
onOpen
method.
3
. Register the message handler in the
onOpen
method.