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; ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access