Unsolicited Notification to Client using WebSocket

One of the biggest advantages of WebSocket is that a server can now push event notifications to clients without any request (or solicitation) from the client. Example of this will be a client that displays live stock prices. When a price changes, the server can push the new price to all clients.

And yet, most Java EE WebSocket examples continue to demonstrate the request-response model. Such as this:

public void onMessage(Session session, String msg) {
 try {
 } catch (IOException e) {

Here, we are sending a message to the client only after the client has sent a request to the server. We don’t really need WebSocket to implement this model. In this article, we will see how a server can send a message to the clients due to some internal events in the business state (such as change in stock price).

First, the theory. Web container creates a new javax.websocket.Session object every time a new client makes a connection. This object stays alive as long as the connection is open. We can use the Session object to send a message back to the client at any time from any thread.

The end point class needs to save the Session objects somewhere so that we can get to them later. Here, we use a HashSet for that.

public class SimpleWSHandler {
 private static final Set<Session> sessions = 
  Collections.synchronizedSet(new HashSet<Session>());

 public void open(Session session) {
  sessions.add(session); //Save the session
 public void close(Session session, CloseReason reason) {
  sessions.remove(session); //Remove the session

Next, we add a method to the end point class that can notify the clients. For example:

public static void broadcastMessage(String message) {
 for (Session s : sessions) {
  if (s.isOpen()) {
   try {
   } catch (IOException e) {

Now, any Java class in your application can fire off a notification to the clients at any time. For example, a Servlet can do this:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
 SimpleWSHandler.broadcastMessage("Hello World");

For a fully working Eclipse project grab this GitHub repository.


One thought on “Unsolicited Notification to Client using WebSocket

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s