A canonical example of using WebSocket is a chat server. This TipOf The Day (TOTD) will share the code for building exactly that!
The complete code in this TOTD can be downloaded here and runs on GlassFish 4 b77.
Here is the code for the Chat Server built as a WebSocket endpoint:
@WebSocketEndpoint("/websocket")
public class ChatEndpoint {
private static final Set<Session> peers = Collections.synchronizedSet(new HashSet<Session>());
@WebSocketOpen
public void onOpen(Session peer) {
peers.add(peer);
}
@WebSocketClose
public void onClose(Session peer) {
peers.remove(peer);
}
@WebSocketMessage
public void message(String message, Session client) throws IOException, EncodeException {
for (Session peer : peers) {
peer.getRemote().sendObject(message);
}
}
}
In this code:
- Lifecycle callbacks manage the coordinates of the connecting clients
message
method receives all the messages sent by the client and then transmits to all the connected clients.
You can use a trivial JavaScript to exchange messages between two browsers. A chat session between two Chrome and Firefox is shown below:
Download the source code and run it in GlassFish 4 b77.