Welcome!

Machine Learning Authors: Pat Romanski, Yeshim Deniz, Liz McMillan, Elizabeth White, Corey Roth

Related Topics: Java IoT, Machine Learning , @ThingsExpo

Java IoT: Blog Feed Post

Pushing Data to Multiple WebSocket Clients From a Java Server By @YFain | @ThingsExpo [#IoT]

Pretty often you need to write a program that publishes the same message to all connected clients

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 spanHTML 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<>());


Read the original blog entry...

More Stories By Yakov Fain

Yakov Fain is a Java Champion and a co-founder of the IT consultancy Farata Systems and the product company SuranceBay. He wrote a thousand blogs (http://yakovfain.com) and several books about software development. Yakov authored and co-authored such books as "Angular 2 Development with TypeScript", "Java 24-Hour Trainer", and "Enterprise Web Development". His Twitter tag is @yfain

CloudEXPO Stories
The technologies behind big data and cloud computing are converging quickly, offering businesses new capabilities for fast, easy, wide-ranging access to data. However, to capitalize on the cost-efficiencies and time-to-value opportunities of analytics in the cloud, big data and cloud technologies must be integrated and managed properly. Pythian's Director of Big Data and Data Science, Danil Zburivsky will explore: The main technology components and best practices being deployed to take advantage of data and analytics in the cloud, Architecture, integration, governance and security scenarios and Key challenges and success factors of moving data and analytics to the cloud
SYS-CON Events announced today that DatacenterDynamics has been named “Media Sponsor” of SYS-CON's 18th International Cloud Expo, which will take place on June 7–9, 2016, at the Javits Center in New York City, NY. DatacenterDynamics is a brand of DCD Group, a global B2B media and publishing company that develops products to help senior professionals in the world's most ICT dependent organizations make risk-based infrastructure and capacity decisions.
The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addresses many of the challenges faced by developers and operators as monolithic applications transition towards a distributed microservice architecture. A tracing tool like Jaeger analyzes what's happening as a transaction moves through a distributed system. Monitoring software like Prometheus captures time-series events for real-time alerting and other uses. Grafeas and Kritis provide security polic...
Most DevOps journeys involve several phases of maturity. Research shows that the inflection point where organizations begin to see maximum value is when they implement tight integration deploying their code to their infrastructure. Success at this level is the last barrier to at-will deployment. Storage, for instance, is more capable than where we read and write data. In his session at @DevOpsSummit at 20th Cloud Expo, Josh Atwell, a Developer Advocate for NetApp, will discuss the role and value extensible storage infrastructure has in accelerating software development activities, improve code quality, reveal multiple deployment options through automated testing, and support continuous integration efforts. All this will be described using tools common in DevOps organizations.
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more business becomes digital the more stakeholders are interested in this data including how it relates to business. Some of these people have never used a monitoring tool before. They have a question on their mind like "How is my application doing" but no idea how to get a proper answer.