O'Reilly logo

JXTA in a Nutshell by Li Gong, Bernard Traversat, Scott Oaks

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Event-Based Programming

In our examples so far, we’ve used synchronous methods to obtain all of our information. When we discovered peergroups or pipe advertisements, we sent the discovery message and then synchronously examined the local cache to see if the resource had been located. When we read messages from the pipe, we blocked until a message was available. Behind the scenes, of course, discovery was asynchronous, but the threads listening for events in that process were hidden to us: all that we invoked were synchronous methods.

However, there is another mechanism available for these calls: an asynchronous, event-based API. This mechanism follows Java’s standard event design pattern: you register a listener class to be informed when certain events occur. When these events occur, methods of the listener class are invoked.

We’ll show how this works by modifying our HungryPeer to use event-based discovery to locate the RestoNet pipes. Here’s the code that does this:

import java.io.*; import java.util.Enumeration; import java.util.Vector; import net.jxta.peergroup.PeerGroup; import net.jxta.peergroup.PeerGroupFactory; import net.jxta.exception.PeerGroupException; import net.jxta.document.AdvertisementFactory; import net.jxta.document.Advertisement; import net.jxta.document.StructuredDocument; import net.jxta.document.Element; import net.jxta.document.StructuredDocumentFactory; import net.jxta.document.MimeMediaType; import net.jxta.discovery.DiscoveryService; import net.jxta.pipe.PipeService; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required