⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 hungrypeer.java

📁 JXTA技术手册 书上3.4.5章的源代码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
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;import net.jxta.pipe.InputPipe;import net.jxta.pipe.PipeID;import net.jxta.pipe.OutputPipe;import net.jxta.endpoint.Message;import net.jxta.protocol.PipeAdvertisement;import net.jxta.protocol.PeerGroupAdvertisement;import net.jxta.id.IDFactory;import net.jxta.membership.MembershipService;import net.jxta.membership.Authenticator;import net.jxta.credential.AuthenticationCredential;import net.jxta.impl.membership.PasswdMembershipService;// The HungryPeer joins the RestoNet PeerGroup and searches for// RestoPeers. The HungryPeer then establishes a pipe connection to// all the RestoPeers that it discovered. The HungryPeer sends// auction requests for French fries to RestoPeers and then waits for// auction bids from RestoPeerspublic class HungryPeer {    private PeerGroup netpg = null;     // NetPeergroup    private PeerGroup restoNet = null;  // Resto Peergroup    // Services within the RestoNet Peergroup    private DiscoveryService disco;     // Discovery Service    private PipeService pipes;          // Pipe Service    private PipeAdvertisement myAdv;    // Hungry peer pipe advertisement    private InputPipe myPipe;           // Input pipe to talk to hungry peer    private MimeMediaType mimeType = new MimeMediaType("text", "xml");    private int timeout = 3000;         // Discovery timeout    private int rtimeout = 30000;       // Pipe Resolver Timeout    // All RestoPeers found    private Vector restoPeerAdvs = new Vector();    private Vector restoPeerPipes = new Vector();    private String myIdentity = "Bill Joy";  // Identity of this HungryPeer    private String friesRequest ="medium";   // Fries Auction request    public static void main(String args[]) {        HungryPeer myapp = new HungryPeer();        myapp.startJxta();        System.exit(0);    }    private void startJxta() {        try {            // Discover (or create) and join the default jxta NetPeerGroup            netpg = PeerGroupFactory.newNetPeerGroup();        } catch (PeerGroupException e) {            //Couldn't initialize; can't continue            System.out.println("Fatal error : creating the NetPeerGroup");            System.exit(1);        }        // Discover and join 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);        }        // Set our HungryPeer communication pipe so RestoPeers        // can talk to us        if (!setHungryPeerPipe()) {            System.out.println(                "Aborting due to failure to create our HungryPeer pipe");            System.exit(1);        }        // Attempt to locate RestoPeers in RestoNet        discoverRestoPeers();        // Connect to RestoPeers that have been discovered        connectToRestoPeers();        // I am hungry. Send an auction request for French Fries        // to the connected RestoPeers.        sendFriesAuctionRequests();        //Process incoming bids from RestoPeers        receiveFriesBids();    }    // 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", "RestoNetAuth");                // 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", "RestoNetAuth", 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);            // 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;        }        authenticateAndJoin(restoNet);        System.out.println("The HungryPeer joined the restoNet PeerGroup");        return true;    }    // Create the HungryPeer pipe to receive bid responses    // from RestoPeers. The advertisement of this pipe is sent as part    // of the auction request for RestoPeers to respond.    private boolean setHungryPeerPipe() {        try {            // Create a pipe advertisement for our hungry peer. This            // pipe will be used within the RestoNet peergroup for other            // peers to talk to our hungry peer            myAdv = (PipeAdvertisement)                AdvertisementFactory.newAdvertisement(                PipeAdvertisement.getAdvertisementType());            // Initialize the advertisement with unique peer information            // So we can communicate            myAdv.setPipeID(IDFactory.newPipeID(restoNet.getPeerGroupID()));            myAdv.setName("restoNet:HungryPipe:" + myIdentity);            // Set the pipe type to be unicast unidrectional            myAdv.setType(PipeService.UnicastType);            // Create the input pipe            myPipe = pipes.createInputPipe(myAdv);        } catch (Exception e) {            System.out.println("Could not create the HungryPeer pipe");            return false;        }        return true;    }    // Discover RestoPeers that have joined RestoNet.    // RestoPeers are discovered via their published pipe advertisement.    private void discoverRestoPeers() {        int found = 0;           // Count of RestoPeers found        int count = 10;          // Discovery retries        System.out.println("Locating RestoPeers in the RestoNet Peergroup");        // Try to find at least two RestoPeers (an arbitrary number)        // RestoPeers are found by their pipe advertisements        while (count-- >0) {            try {                // Check if we already have restaurant advertisements                // in our local peer cache                Enumeration ae =                    disco.getLocalAdvertisements(DiscoveryService.ADV,                                     "name", "RestoNet:RestoPipe:*");

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -