天天看點

JXTA技術手冊 服務通告Resto/Hungry執行個體

由于版本的不同,書中的例子不能再Eclipse中正常運作。我們将例子改寫為:

RestoPeer.java:

import java.io.*;
import java.net.*;
import java.util.*;

import net.jxta.peergroup.PeerGroup;
import net.jxta.peergroup.NetPeerGroupFactory;
import net.jxta.peergroup.PeerGroupID;
import net.jxta.exception.PeerGroupException;
import net.jxta.discovery.DiscoveryService;
import net.jxta.id.IDFactory;
import net.jxta.pipe.PipeService;
import net.jxta.protocol.PeerGroupAdvertisement;
import net.jxta.protocol.ModuleImplAdvertisement;

// RestoPeer represents a restaurant that receives auction requests
// for food from HungryPeers. The RestoPeer will discover and join
// the RestoNet and publish itself as a provider for HungryPeers

public class RestoPeer {

    private PeerGroup netpg = null;     // The NetPeerGroup
    private PeerGroup restoNet = null;  // The RestoNet Peergroup
    private String brand = "Chez JXTA";  // Brand of my restaurants
    private int timeout = 3000;          // Timeout; can be adjusted

    // Services within the RestoNet peergroup
    private DiscoveryService disco = null;  // Discovery service
    private PipeService pipes = null;       // Pipe service
    static String groupURL = "jxta:uuid-4d6172676572696e204272756e6f202002"; 

    public static void main(String args[]) {
        RestoPeer myapp = new RestoPeer();
        myapp.startJxta();
        System.exit(0);
    }

    // start the JXTA application
    private void startJxta() {
        try {
            // Discover and join (or start) the default peergroup
            netpg = (new NetPeerGroupFactory()).getWeakInterface();
        } catch (PeerGroupException e) {
            // Couldn't initialize; can't continue
            System.out.println("Fatal error : creating the net PeerGroup");
            System.exit(1);
        }

        // Discover (or create) and join the RestoNet peergroup
        try {
            joinRestoNet();
        } catch (Exception e) {
            System.out.println("Can't join or create RestoNet");
            System.exit(1);
        }

        // Wait for HungryPeers
        System.out.println("Waiting for HungryPeers");
        while (true) {
            // In later examples, HungryPeer requests are processed here
        }
    }

    // Discover (or crete) and join the RestoNet peergroup
    private void joinRestoNet() throws Exception {

        int count = 3;   // maximun number of attempts to discover
        System.out.println("Attempting to Discover the RestoNet PeerGroup");

        // Get the discovery service from the NetPeergroup
        DiscoveryService hdisco = netpg.getDiscoveryService();

        Enumeration ae = null;  // Holds the discovered peers

        // Loop until we discover the RestoNet or
        // until we've exhausted the desired number of attempts
        while (count-- > 0) {
            try {
                // search first in the peer local cache to find
                // the RestoNet peergroup advertisement
                ae = hdisco.getLocalAdvertisements(DiscoveryService.GROUP,
                                          "Name", "RestoNet");

                // If we found the RestoNet advertisement we are done
                if ((ae != null) && ae.hasMoreElements())
                    break;

                // If we did not find it, we send a discovery request
                hdisco.getRemoteAdvertisements(null,
                       DiscoveryService.GROUP, "Name", "RestoNet", 1, null);

                // Sleep to allow time for peers to respond to the
                // discovery request
                try {
                    Thread.sleep(timeout);
                } catch (InterruptedException ie) {}
            } catch (IOException e) {
                // Found nothing! Move on.
            }
        }

        PeerGroupAdvertisement restoNetAdv = null;

        // Check if we found the RestoNet advertisement.
        // If we didn't, then either
        //       we are the first peer to join or
        //       no other RestoNet peers are up.
        // In either case, we must create the RestoNet peergroup

        if (ae == null || !ae.hasMoreElements()) {
            System.out.println(
                 "Could not find the RestoNet peergroup; creating one");
            try {

                // Create a new, all-purpose peergroup.
                ModuleImplAdvertisement implAdv =
                    netpg.getAllPurposePeerGroupImplAdvertisement();
                restoNet = netpg.newGroup(
                                mkGroupID(),      // Assign new group ID
                                implAdv,          // The implem. adv
                                "RestoNet",       // Name of peergroup
                                "RestoNet, Inc.");// Description of peergroup

                // Get the PeerGroup Advertisement
                restoNetAdv = netpg.getPeerGroupAdvertisement();

            } catch (Exception e) {
                System.out.println("Error in creating RestoNet Peergroup");
                throw e;
            }
        } else {
            // The RestoNet advertisement was found in the cache;
            // that means we can join the existing RestoNet peergroup

            try {
                restoNetAdv = (PeerGroupAdvertisement) ae.nextElement();
                restoNet = netpg.newGroup(restoNetAdv);
                 System.out.println(
                     "Found the RestoNet Peergroup advertisement; joined existing group");
            } catch (Exception e) {
                System.out.println("Error in creating RestoNet PeerGroup from existing adv");
                throw e;
            }
        }

        try {
            // Get the discovery and pipe services for the RestoNet Peergroup
            disco = restoNet.getDiscoveryService();
            pipes = restoNet.getPipeService();
        } catch (Exception e) {
            System.out.println("Error getting services from RestoNet");
            throw e;
        }

        System.out.println("RestoNet Restaurant (" + brand + ") is on-line");
        return;
    }

    private PeerGroupID mkGroupID() throws Exception {
    	return (PeerGroupID) IDFactory.fromURI( new URI ("urn" + ":" + groupURL));
    }
}
           

HungryPeer,java

import java.io.*;
import java.util.Enumeration;
import java.util.Vector;

import net.jxta.peergroup.PeerGroup;
import net.jxta.peergroup.NetPeerGroupFactory;
import net.jxta.exception.PeerGroupException;
import net.jxta.document.AdvertisementFactory;
import net.jxta.document.Advertisement;
import net.jxta.discovery.DiscoveryService;
import net.jxta.pipe.PipeService;
import net.jxta.protocol.PeerGroupAdvertisement;

// HungryPeer tries to find a restaurant to
// get a good meal. It finds all RestoPeers in
// the RestoNet peergroup and (in later examples)
// requests bids from them.

public class HungryPeer {

    private PeerGroup netpg = null;     // NetPeergroup
    private PeerGroup restoNet = null;  // Resto Peergroup
    private int timeout = 3000;         // Timeout; can be adjusted

    // Services within the RestoNet Peergroup
    private DiscoveryService disco;     // Discovery Service
    private PipeService pipes;          // Pipe Service

    // Vector of discovered RestoPeers
    private Vector restaurantAdvs = new Vector();

    public static void main(String args[]) {
        HungryPeer myapp = new HungryPeer();
        myapp.startJxta();
        System.exit(0);
    }

    // Start the JXTA application
    private void startJxta() {
        try {
            // Discover (or create) and join the default jxta NetPeerGroup
            netpg = (new NetPeerGroupFactory()).getWeakInterface();
        } catch (PeerGroupException e) {
            // Couldn't initialize; can't continue
            System.out.println("Fatal error : creating the net PeerGroup");
            System.exit(1);
        }

        // Discover and join the RestoNet Peergroup
        // HungryPeers never create the RestoNet peergroup
        try {
            if (!joinRestoNet()) {
                System.out.println("Sorry could not find the RestoNet Peergroup");
                System.exit(2);
            }
        } catch (Exception e) {
            System.out.println("Can't join RestoNet group");
            System.exit(1);
        }
    }

    // This method is used to discover the RestoNet Peergroup.
    // If found the peer will join the peergroup
    private boolean joinRestoNet() {

        int count = 3; // maximum number of attempts to discover

        System.out.println("Attempting to discover the RestoNet Peergroup");

        // Get the Discovery service handle from the NetPeerGroup
        DiscoveryService hdisco = netpg.getDiscoveryService();

        // All discovered RestoNet Peers
        Enumeration ae = null;

        // Loop until we find the "RestoNet" Peergroup advertisement
        // or we've exhausted the desired number of attempts
        while (count-- > 0) {
            try {
                // Check if we have the advertisement in the local
                // peer cache
                ae = hdisco.getLocalAdvertisements(DiscoveryService.GROUP,
                                            "Name", "RestoNet");

                // If we found the RestoNet advertisement, we are done
                if ((ae != null) && ae.hasMoreElements())
                    break;

                // The RestoNet advertisement is not in the local
                // cache . Send a discovery request to search for it.
                hdisco.getRemoteAdvertisements(null,
                       DiscoveryService.GROUP, "Name", "RestoNet", 1, null);

                // Wait to give peers a chance to respond
                try {
                    Thread.sleep(timeout);
                } catch (InterruptedException ie) {}
            } catch (IOException e) {
                // Found nothing! Move on.
            }
        }

        // Check if we found the RestoNet advertisement
        if (ae == null || !ae.hasMoreElements()) {
            return false;
        }

        System.out.println("Found the RestoNet PeerGroup Advertisement");
        // Get the advertisement
        PeerGroupAdvertisement adv =
            (PeerGroupAdvertisement) ae.nextElement();

        try {
            // Call the PeerGroup Factory to instantiate a new
            // peergroup instance
            restoNet = netpg.newGroup(adv);
        } catch (Exception e) {
          System.out.println("Could not create RestoPeerGroup");
          return false;
        }

        try {
            // Call the PeerGroup Factory to instantiate a new
            // peergroup instance
            restoNet = netpg.newGroup(adv);

            // Get the Discovery and Pipe services to
            // be used within the RestoNet Peergroup
            disco = restoNet.getDiscoveryService();
            pipes = restoNet.getPipeService();
        } catch (Exception e) {
          System.out.println("Could not create RestoPeerGroup");
          return false;
        }

        System.out.println("The HungryPeer joined the restoNet PeerGroup");
        return true;
    }
}
           

主要的更改有:

1. 建立NetPeerGroup的方法和引用的頭檔案都改變了:netpg = (new NetPeerGroupFactory()).getWeakInterface();

2. Get ID 的fromURL函數更新為fromURI:return (PeerGroupID) IDFactory.fromURI( new URI ("urn" + ":" + groupURL));

測試成功。

下一篇: JXTA初探