Pushing data to multiple WebSocket clients from a Java server

Finished writing the WebSocket chapter for the second edition of my Java 24 Hour Trainer. In this blog I’ll show you one of the code samples from lesson 28.

Pretty often you need to write a program that publishes the same message to all connected clients. For example, multiple clients of the online auctions have to be notified when a new bid is placed on the product. Another example is when a new stock price quote need to be pushed from the server to all connected clients. With websockets it’s a pretty easy task.

I’ll show you a basic example when a WebSocket endpoint pushes the server’s time to all connected clients. If you can publish the server’s time to all connected clients, you can publish any application-specific data.

The following endpoint WebSocketClock schedules the task that gets and formats the server’s time every second and publishes the time to all connected clients. I schedule this timer once when the first client connects to our endpoint. The method sendTimeToAll() finds all connected clients by invoking getOpenSessions() on the Session object. Then on each session it calls getBasicRemote().sendText().

@ServerEndpoint("/clock")
public class WebSocketClock { 

  static ScheduledExecutorService timer = 
       Executors.newSingleThreadScheduledExecutor(); 

  private static Set<Session> allSessions; 

  DateTimeFormatter timeFormatter =  
          DateTimeFormatter.ofPattern("HH:mm:ss");
  @OnOpen   
  public void showTime(Session session){
      allSessions = session.getOpenSessions();

      // start the scheduler on the very first connection
      // to call sendTimeToAll every second   
      if (allSessions.size()==1){   
        timer.scheduleAtFixedRate(
             () -> sendTimeToAll(session),0,1,TimeUnit.SECONDS);    
      }
     }      

   private void sendTimeToAll(Session session){       
     allSessions = session.getOpenSessions();
     for (Session sess: allSessions){          
        try{   
          sess.getBasicRemote().sendText("Local time: " + 
                    LocalTime.now().format(timeFormatter));
          } catch (IOException ioe) {        
              System.out.println(ioe.getMessage());         
          }   
     }   
  }
}

The Web client is pretty simple. On the page load the JavaScript code connects to the WebSocket endpoint on the server. The callback onMessage() is invoked when the message (current time) arrives. In this callback I update the content of the span HTML element with the current time. Since my Java code will send the message every second, the span content updates with this frequency. No page refreshes, no heavy HTTP headers, no AJAX long polling hacks either.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
  <span id="messageGoesHere"></span>
  
  <script type="text/javascript">
    var ws = new WebSocket("ws://localhost:8080/Lesson28/clock"); 
       
    ws.onmessage = function(event) {
      var mySpan = document.getElementById("messageGoesHere");
      mySpan.innerHTML=event.data; 
    };
    
    ws.onerror = function(event){
        console.log("Error ", event)
    }  
</script>
</body>
</html>

The next screenshot shows how Eclipse internal browser, Chrome, and Firefox display the current time published by my WebSocket endpoint.

f28_6

Three Web clients get current time published by a WebSocket endpoint every second.

Iterating through all open sessions works fine if the number of connected clients is small. But if you have hundreds of clients, consider grouping the Session objects into separate collections in @OnOpen message handler, and sending messages to each group in parallel from multiple threads. Important: by default, a Java EE server creates a new instance of the server endpoint class for each client’s connection, so if you’ll be creating your own session collections they must be static:

 
private static Set<Session> sessionsChunk1 = Collections.synchronizedSet(new HashSet<>());
private static Set<Session> sessionsChunk2 = Collections.synchronizedSet(new HashSet<>());
Advertisements

Submitted a proposal to IoT track at Cloud Expo New York

In June a large expo and a conference Cloud Computing comes back Javits Center in Manhattan. This year it includes a new track Internet of Things, which promises to be “The Next Big Thing”. In our company we have enough of early adopters of anything related to software development, and we’d like to present what we can do in this field. Here’s the proposal I just submitted to the IoT Expo:

ABSTRACT

Case Study. IoT In The Field Force Automation

From software development perspective IoT is about programming “things”, about connecting them with each other or integrating them with existing applications. This case study will show you how small IoT-enabled devices from multiple manufacturers can be integrated into workflow of an enterprise application. This is a practical demo of building a framework and components in HTML/Java/Mobile technologies to serve as a platform that can integrate new devices as they become available on the market.

BIO

Yakov Fain is a co-founder of two software companies: Farata Systems and SuranceBay. He authored several technical books and lots of articles on software development. Yakov is Java Champion. He leads Princeton Java Users Group. Two of Yakov’s books will go in print this year: “Enterprise Web Development” (O’Reilly) and “Java For Kids” (No Starch Press).

Keeping my fingers crossed…

Java Swing Has to be Deprecated

Every time I start teaching my new Java class I’m looking at the Swing units in the manual asking myself, “Why my students need to know Swing framework?” Well, I need to teach them how to program GUI, event listeners, asynchronous worker threads and event loop that are pretty much the same in every programming language that deals with UI. My students create applets and test them in appletviewer, then they are going through hard times trying to run them in Web browsers… In the end, I tell them that they won’t be going doing Swing programming in the real world projects. I also tell them that if Amazon.com would decide to re-write their UI in Java they’d be out of business in no time.

If not with Swing framework, how should my Java students learn GUI programming? There is another Oracle product called JavaFX. It’s a better looking wrapper for Swing. It still runs on JVM, so Amazon would go out of business as quickly as with Swing, but at least with a better looking UI.

Java developers look down at the HTML/JavaScript crowd. Yes, programming in JavaScript is not as productive as in Java, but HTML5 applications usually look nice. HTML5 developers know that having a Web designer producing professionally looking CSS is a must. Whereas Swing components are ugly by default. They are so last century.

Recently I was attending a presentation on a particular Eclipse plugin that could produce Web reports. The speaker was using Twitter API to demonstrate how easy it was to generate a report finding tweets based on a certain hashtag. Tada….Report is generated, the Web browser opens the report’s URL and pops up the modal dialog asking to enter the search parameter. What an ugly dialog box that was! Eclipse grey style, 90% of its real estate was empty with an input field on top prompting to enter the parameter’s value. No one in the audience (all Java developers) seemed to care. They are all used to ugly GUI in enterprise applications. OK, this product was using RCP UI components, but the Swing ones are definitely not better.

The sooner Swing is deprecated the better. Even if JavaFX has no future in the Web or mobile applications, it has to become a mandatory replacement for Swing. Just because it promotes a better looking UI. Just because it promotes better taste among Java developers, who live in two different realities: the ugly depressive GUI at work and the eye candy world of iOS or Android applications. Let’s make a first step toward merging these worlds by killing Java Swing framework.

How we write a book for O’Reilly

In the past, to write a book the writer would need a quill pen. After a while, Microsoft Word replaced the goose feather. Today, any Word processor is not good enough. You need to have tools to generate the book content in various formats to be read on various devices. Things get complicated if you have more than one writer working on the book. Now you need a distributed version control system.

We’ve recorded a Webcast showing how we write a technical book for O’Reilly Media. This Webcast is not about the book itself, but rather about the process of writing the book and the software tools we use for it.

The recording is available here. This is an interactive recording – you can switch it to the full screen mode.

HTML5, PowerPoint, and the Real World

If you are going to attend any HTML5 conference, most likely you’ll see some of the speakers using Web browsers for presentation slides. The audience likes it cause it’s cool. A month ago one of our software engineers presented this way at the conference for Web developers.

There is an extra benefit in using such html-based slides especially when your presentation is about Web applications. Just think about it, when the time comes for a demo, you are not leaving the Web browser – the next “slide” has the URL of your demo right in the address bar of your browser and you do the demo right there. Hit the right arrow, and the demo turns into a slide again. Isn’t it cool? Yes it’s cool, but not practical.

Because everything else in not as cool and requires a lot of work comparing to Microsoft’s PowerPoint or Apple’s Keynote. Say, you want to add an image to the slide, make it smaller, and move it to the top right corner of the slide. In Powerpoint your hand just does it automatically. In HTML slides it’s a project. How about font manipulations? In Powerpoint you don’t even think about it – you just do it. In HTML slides it’s a project.

Animations? Which one you want? Just pick one from a dozen that are readily available in PowerPoint. You want the image to fly from the top, bounce a couple of times and settle in the middle? Takes 10 seconds to pick the image, 20 seconds for testing, and another 5 second to remove this flashy-bouncy-flying effect cause it would make your audience dizzy. I’m sure this will be easy in the HTML6 era, but the HTML5 tooling is not there yet.

How about embedding media into slides? OK, ok, you got the message.

Next week I’ll need to find some time to migrate that HTML presentation into the tried and true PowerPoint slide deck. Yes, I’ll be switching from PowerPoint to the Web Browser when the time will come for the demo. This is a drawback. But every other aspect of making a presentation in PowerPoint or Keynote is superior to HTML.

I’m observing the same situation in the enterprise world, where some IT managers are diving into new HTML5 project without thinking about the consequences. If you guys want to be cool, just dive right into the cold water.

If you want to develop an application that will contain 100% of the required functionality – wait a couple of years for HTML5 tooling to mature. But if you want to be cool now, eliminate half of the required functionality and do your 100-screen enterprise Web application in HTML5.

Today, at the meeting with a prospective client I said that if you decide to implement the same functionality in HTML5 vs. a mature platform with a compiled language and predictable VM, multiply the development time by two. Now I’m thinking I was wrong. The time should be tripled.

The Cover and the Epilogue of the Upcoming Book

Our publisher sent us for approval the image of a cover of the upcoming book on Web development. We were told that the name of the bird is Roseate Spoonbill. Why they decided that Roseate Spoonbill should be associated Web development will remain a mystery. I guess, since the beak of this birdy is pointing at the word “Web”, the customer of the book store should think to himself, “Hmm, I have no idea what kind of bird this is and I don’t know how to develop for the Web. Let me buy this book!” In the unlikely event that you’re also not overly familiar with Roseate Spoonbill, please refer to THE SOURCE.

cover

But this cover pales in comparison with the book epilogue. This book is about HTML5, and one would expect some drum roll and fanfares praising HTML5. Here’s what the current version of the book epilogue reads:


Epilogue

Even though this book is about HTML5, the authors would rather work with compiled languages that produce applications to run in virtual machines. Such software platforms are more productive for development and more predictable for deployment. While writing this book we were often arguing about pros and cons of switching to HTML5, and so far we are concerned that the HTML/JavaScript/CSS platform is not ready for developing of the enterprise applications just yet. We live in the era when amateurs feel comfortable creating Web sites and that JavaScript provides flexibility and customization the Access and Excel provided in the old good PC times.

Till this day Microsoft Excel is the most popular application among business users in the enterprises. They start the application locally, it has a local storage that enables work in the occasionally-connected scenarios. Both the data and the code are physically located close to the user’s heart. Microsoft Excel allows the users to have her own little pieces of data and amateurish-but-working-code (a.k.a. formulas) very close and personal. Right on the desktop. No need to ask these IT prima donnas for favors. No dependencies on the connectivity or some mysterious servers being slow or down. The most advanced business users even learn how to operate MS Access database to further lessen the dependency on IT.

But there is only so much you can do with primitive tools. Visual Basic was “JavaScript” of the nineties – it had similar problems, but nevertheless had huge followings. Now the same people are doing JavaScript. If we don’t break this cycle by adopting a common to all browsers VM, we are doomed for going through the generation after generation of underpowered crap. We wrote this book to help people with understanding of what HTML5 applications are about. But make no mistakes – the world of HTML5 is not a peachy place in the future preached by educated and compassionate scientists, but rather a nasty past that is catching up bringing the mob with it.

Most likely the publisher won’t let this epilogue to finish the book, and this blog will remain the only place this text will be published. Amen, bro!