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

📄 jailgameclient.java

📁 Java P2P技术内幕:《Java P2P技术内幕》源码
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
            Thread.sleep(5 * 1000);        } catch (Exception ignore) {}        // Check to make sure the peer exists.        Iterator iterator = jailPeerSet.iterator();        boolean peerExists = false;        // Find the peer's PeerAdvertisement        while (iterator.hasNext()) {            PeerAdvertisement adv = (PeerAdvertisement) iterator.next();            if (adv.getName().equals(peerName)) {                peerExists = true;                break;            }        }        String msg = (!peerExists) ?             "Warning:  Peer " + peerName + " may not exist.\n" +            "Attempting to transfer anyways." :             "Transfering key to peer: " + peerName;        System.out.println(msg);        DiscoveryService jailDiscoverySvc =             jailPeerGroup.getDiscoveryService();        DiscoveryListener listener = new DiscoveryListener() {                /**                 * Creates the output pipe that connects to the peer we wish                 * to send the jail token to.  Then sends the jail token via                 * the "key" element.                 */                public void discoveryEvent(DiscoveryEvent ev)                {                    DiscoveryResponseMsg res = ev.getResponse();                    Enumeration enum = res.getResponses();                    while (enum.hasMoreElements()) {                        String advString = (String) enum.nextElement();                        OutputPipe outputPipe = null;                        try {                            PipeAdvertisement pipeAdv = (PipeAdvertisement)                                AdvertisementFactory.newAdvertisement(new MimeMediaType("text/xml"), new ByteArrayInputStream (advString.getBytes()));                            PipeService pipeSvc = jailPeerGroup.getPipeService();                            outputPipe = pipeSvc.createOutputPipe(pipeAdv, 1000);                            // Create the actual message with the key and sender                            Message message = pipeSvc.createMessage();                            MessageElement messageElement = message.newMessageElement("key", new MimeMediaType("text/plain"), new ByteArrayInputStream(jailTokenString.getBytes()));                            message.addElement(messageElement);                            MessageElement senderElement = message.newMessageElement("sender", new MimeMediaType("text/plain"), new ByteArrayInputStream(jailPeerGroup.getPeerName().getBytes()));                            message.addElement(senderElement);                            outputPipe.send(message);                            JailGameClient.this.hasJailToken = false;                            return;                        } catch (Exception e) {                            e.printStackTrace();                        } finally {                            if (outputPipe != null) {                                outputPipe.close();                            }                        }                    }                }            };        String name = JailGameClient.JAIL_TRANSFER_KEY + ":" + peerName;        jailDiscoverySvc.getRemoteAdvertisements(null, DiscoveryService.ADV,                                                 "name", name, 10, listener);        // Now sleep for the transfer to finish        try {            Thread.sleep(10 * 1000); // we may want to sleep longer        } catch (Exception ignore) { }        return !this.hasJailToken;    }    /**     * This method is used to clean up all the resources so we can start from scratch.     */    private void cleanResources()    {        this.inputUnicastPipe.close();        this.unicastListener = null;        this.jailPeerSet.clear();        this.groupFound = false;        this.inJail = false;        this.pipeAdvFound = false;        this.hasJailToken = false;        this.jailTokenString = null;        ResolverService resolverSvc = this.jailPeerGroup.getResolverService();        resolverSvc.unregisterHandler(JailGameClient.JAIL_KEY_QUERY_HANDLER);        resolverSvc.unregisterHandler(JailGameClient.JAIL_KEY_LOCATOR_HANDLER);        this.jailPeerGroup = null;    }    /**     * A utility method to print out the contents of an advertisement.     */    public static void printAdvertisement(Advertisement adv)    {        try {            Document doc = adv.getDocument(new MimeMediaType("text/plain"));            ByteArrayOutputStream output = new ByteArrayOutputStream();            doc.sendToStream(output);            System.out.println(output.toString());//             BufferedInputStream stream = new BufferedInputStream(doc.getStream());//             StringBuffer buffer = new StringBuffer();//             byte [] bytes = new byte[stream.available()];//             while ((c = stream.readChar())!= null) {//                 buffer.append(c);//             }//             System.out.println(buffer.toString());        } catch (Exception ignore) {            ignore.printStackTrace();        }    }    /**     * Start up the Net Peer group & get the Discovery Service for that group.     */    public void startJxta()        throws PeerGroupException, IOException    {        this.netPeerGroup = PeerGroupFactory.newNetPeerGroup();        this.discoverySvc = netPeerGroup.getDiscoveryService();        // Flush all local cache information.  We want to start from scratch.        discoverySvc.flushAdvertisements(null, DiscoveryService.ADV);        discoverySvc.flushAdvertisements(null, DiscoveryService.PEER);        discoverySvc.flushAdvertisements(null, DiscoveryService.GROUP);    }    public void run()    {        try {            if (createOrJoin == JailGameClient.JOIN_GAME) {                discoverJailGroup();            } else { // Create the group.  Add a propagate PIPE Advertisement to it.                jailPeerGroup = createGroup(JailGameClient.JAIL_GROUP);                this.hasJailToken = true;                // the token is just the current time :)                this.jailTokenString = "" + System.currentTimeMillis();                publish(jailPeerGroup.getPeerGroupAdvertisement(),                        DiscoveryService.GROUP);            }            // Publish the unicast pipe used to send the jail token to others.            createJailUnicastPipeAdv();            publishJailAdv(jailUnicastPipeAdv, DiscoveryService.ADV);            // Start the RendezVousService            //netPeerGroup.getRendezVousService().startRendezVous();            //jailPeerGroup.getRendezVousService().startRendezVous();        } catch (Exception e) {            String errMsg = "Unable to start create or join jail group.";            System.out.println(errMsg);            e.printStackTrace();                        return;        }        if (!joinPeerGroup(jailPeerGroup)) {            return;        }                try {            this.createPipes();        } catch (Exception ex) {            String errMsg = "Unable to create broadcast pipes";            System.out.println(errMsg);            ex.printStackTrace();            return;        }        setResolverHandler();                // This is the user interface menu.        for (;;) {            BufferedReader reader =                new BufferedReader(new InputStreamReader(System.in));            String lineToSend = null;            System.out.print("Type H for help\n:>");            try {                while ((lineToSend = reader.readLine()) != null) {                    lineToSend = lineToSend.trim();                    if (lineToSend.equals("")) {                        System.out.print(":>");                        continue;                    }                    if (!inJail && !lineToSend.equalsIgnoreCase("Q")) {                        System.out.println("You are not in jail.  You can only quit");                        System.out.print(":>");                        continue;                    }                    StringTokenizer tokenizer =                        new StringTokenizer(lineToSend);                    String command = tokenizer.nextToken();                    if (command.equalsIgnoreCase("L")) {                        if (!tokenizer.hasMoreTokens()) {                            System.out.println("Peer name missing");                        } else {                            String peerName = tokenizer.nextToken();                            leaveJail(peerName);                        }                    } else if (command.equalsIgnoreCase("R")) {                        requestJailToken();                    } else if (command.equalsIgnoreCase("P")) {                        printPeers();                    } else if (command.equalsIgnoreCase("F")) {                        findJailToken();                    } else if (command.equalsIgnoreCase("T")) {                        if (!tokenizer.hasMoreTokens()) {                            System.out.println("Client name missing");                        } else {                            String peerName = tokenizer.nextToken();                            transferJailKey(peerName);                        }                    } else if (command.equalsIgnoreCase("H")) {                        printHelp();                    } else if (command.equalsIgnoreCase("Q")) {                        quit();                    }                                    System.out.print(":>");                }            } catch (Exception io) {                io.printStackTrace();            }        }    }    public void printHelp()    {        String help = "H - print this help\nF - find who has the token\nR - request jail token\nP - print peers\nT <client> - transfer jail token to client\nL <client> - leave jail and send jail token to client\nQ - quit application\n";        System.out.println(help);    }    public static void main (String argc[])        throws Exception    {        if (argc.length < 1) {            String msg = "Usage: " + JailGameClient.class.getName()                + " [join/create]";            System.out.println(msg);            return;        }        int createOrJoin = (argc[0].equals("join")) ?            JailGameClient.JOIN_GAME : JailGameClient.CREATE_GAME ;        JailGameClient client = new JailGameClient(createOrJoin);        client.startJxta();        Thread thread = new Thread(client);        thread.start();    }}

⌨️ 快捷键说明

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