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

📄 restopeer.java

📁 JXTA技术手册 书上3.4.5章的源代码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
                }                // We received a message; extract the request                try {                    // Extract the HungryPipe pipe information                    // to reply to the sender                    ip = msg.getElement("HungryPeerPipe").getStream();                    // Construct the associated pipe advertisement                    // via the AdvertisementFactory                    hungryPipe = (PipeAdvertisement)                    AdvertisementFactory.newAdvertisement(mimeType, ip);                    // Extract the sender name and fries size requested                    // building a StructuredDocument                    ip = msg.getElement("Request").getStream();                    request = StructuredDocumentFactory.newStructuredDocument                                    (mimeType, ip);                    // Extract the fields from the structured Document                    Enumeration enum = request.getChildren();                    // Loop over all the elements of the document                    while (enum.hasMoreElements()) {                        el = (Element) enum.nextElement();                        String attr = (String) el.getKey();                        String value = (String) el.getValue();                        // Extract the HungryPeer Requester Name                        if (attr.equals("Name")) {                            name = value;                            continue;                        }                        // Extract the Fries  size requested                        else if (attr.equals("Fries")) {                            size = value;                            continue;                        }                    }                } catch (Exception e) {                    continue; // Broken content; silently discard                }                System.out.println("Received Request from HungryPeer "                               + name                               + " for "                               + size                               + " Fries.");                // The auction request is valid. We can                // create the output pipe to send the response bid to                // the HungryPeer requester                try {                    System.out.println(                        "Attempting to create Output Pipe to HungryPeer " +                        name);                    // Create an output pipe connection to the HungryPeer                    pipeOut = pipes.createOutputPipe(hungryPipe,                                                     rtimeout);                    // Check if we have a pipe                    if (pipeOut == null) {                        // Cannot conect the pipe                        System.out.println("Could not find HungryPeer pipe");                        continue;                    }                } catch (Exception e) {                    // Pipe creation exception                    System.out.println("HungryPeer may not be listening anymore");                    continue;                }                // We have a pipe connection to the HungryPeer.                // Now create the Bid Response document                try {                    // Construct the Response document                    bid = StructuredDocumentFactory.newStructuredDocument(                                     mimeType,                                     "RestoNet:Bid");                    // Set the Bid values (Brand, price, special)                    // in the response document                    el = bid.createElement("Brand", brand);                    bid.appendChild(el);                    el = bid.createElement("Price", friesPrice(size));                    bid.appendChild(el);                    el = bid.createElement("Specials", specials);                    bid.appendChild(el);                    // Create a new pipe message                    msg = pipes.createMessage();                    // Push the Bid offer in the message                    msg.addElement(msg.newMessageElement(                                   "Bid",mimeType, bid.getStream()));                    // Send the message                    pipeOut.send(msg);                    // Close the output pipe connection                    pipeOut.close();                } catch (Exception ex) {                    System.out.println(                        "Error sending bid offer to HungryPeer " + name);                    continue;                }                System.out.println("Sent Bid Offer to HungryPeer (" + name +                       ") Fries price = "  + friesPrice(size) +                       ", special = " + specials);            } catch (Exception e) {               System.out.println("Abort RestoPeer interrupted");               return;            }        }    }    // Determine the price of the French fries depending on the size    private String friesPrice(String size) {        if (size.equals("small"))              return "$1.50";        if (size.equals("medium"))              return "2.50";        if (size.equals("large"))              return "3.00";        return "error";    }    // Create the resto pipe associated with this RestoPeer.    // Discover first if a pipe advertisement exists, if    // not create and publish it.    private boolean createRestoPipe() {        int count = 3;           // Discovery retry count        Enumeration ae = null;   // Discovery response enumeration        try {            System.out.println(                "Attempting to Discover the Restaurant RestoPipe");            // Check if I have already published myself            while (count-- > 0) {                try {                    // Check first locally if we have the advertisement cached                    ae = disco.getLocalAdvertisements(DiscoveryService.ADV,                                      "name", "RestoNet:RestoPipe:" + brand);                    // If we found our pipe advertisement we are done                    if (ae != null && ae.hasMoreElements())                        break;                    // We did not find the advertisement locally;                    // send a remote request                    disco.getRemoteAdvertisements(null,                          DiscoveryService.ADV, "name",                          "RestoNet:RestoPipe:" + brand, 1, null);                    // Sleep to allow time for peers to respond to the                    // discovery request                    try {                        Thread.sleep(timeout);                    } catch (InterruptedException e) {}                } catch (IOException e) {                    // Found nothing! Move on                }            }            if (ae == null || !ae.hasMoreElements()) {                // We did not find the pipe advertisement, so create one                System.out.println(                    "Could not find the Restaurant Pipe Advertisement");                // Create a pipe advertisement for our RestoPeer                myAdv = (PipeAdvertisement)                    AdvertisementFactory.newAdvertisement(                        PipeAdvertisement.getAdvertisementType());                // Assign a unique ID to the pipe                myAdv.setPipeID(                        IDFactory.newPipeID(restoNet.getPeerGroupID() ));                // The symbolic name of the pipe is built from                // the brand name of RestoPeer;  each RestoPeer                // must therefore have a unique name.                myAdv.setName("RestoNet:RestoPipe:" + brand);                // Set the type of the pipe to be unidirectional                myAdv.setType(PipeService.UnicastType);                // We have the advertisement; publish it                // into our local cache and to the RestoNet PeerGroup.                // We use the default lifetime and the default                // expiration time for remote publishing                disco.publish(myAdv, DiscoveryService.ADV,                              PeerGroup.DEFAULT_LIFETIME,                              PeerGroup.DEFAULT_EXPIRATION);                disco.remotePublish(myAdv, DiscoveryService.ADV,                              PeerGroup.DEFAULT_EXPIRATION);                System.out.println(                    "Created the Restaurant Pipe Advertisement");            } else {                // We found an existing pipe advertisement                myAdv = (PipeAdvertisement) ae.nextElement();                System.out.println("Found Restaurant Pipe Advertisement");            }            // Create my input pipe to listen for hungry peers            // requests            pipeIn = pipes.createInputPipe(myAdv);        } catch (Exception e) {            System.out.println("Could not initialize the Restaurant pipe");            return false;        }        return true;    }    private PeerGroupID mkGroupID() throws Exception {        return (PeerGroupID) IDFactory.fromURL(             new URL("urn", "", groupURL));    }}

⌨️ 快捷键说明

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