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

📄 jailgameclient.java

📁 由Robert Flenner,Michael Abbott,Toufic Boubez,Frand Cohen,Navaneeth Krishnan,Alan Moffet,Rajam Famamu
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
import java.util.*;import java.io.*;import net.jxta.id.IDFactory;import net.jxta.pipe.InputPipe;import net.jxta.pipe.PipeMsgEvent;import net.jxta.pipe.PipeMsgListener;import net.jxta.credential.AuthenticationCredential;import net.jxta.document.StructuredDocument;import net.jxta.document.Document;import net.jxta.document.StructuredTextDocument;import net.jxta.document.MimeMediaType;import net.jxta.membership.Authenticator;import net.jxta.membership.MembershipService;import net.jxta.peergroup.PeerGroup;import net.jxta.peergroup.PeerGroupFactory;import net.jxta.exception.PeerGroupException;import net.jxta.exception.ProtocolNotSupportedException;import net.jxta.document.AdvertisementFactory;import net.jxta.document.MimeMediaType;import net.jxta.discovery.DiscoveryService;import net.jxta.discovery.DiscoveryListener;import net.jxta.discovery.DiscoveryEvent;import net.jxta.pipe.PipeService;import net.jxta.pipe.OutputPipe;import net.jxta.pipe.OutputPipeListener;import net.jxta.pipe.OutputPipeEvent;import net.jxta.protocol.DiscoveryResponseMsg;import net.jxta.protocol.PipeAdvertisement;import net.jxta.protocol.PeerGroupAdvertisement;import net.jxta.protocol.ModuleImplAdvertisement;import net.jxta.protocol.PeerAdvertisement;import net.jxta.protocol.ResolverQueryMsg;import net.jxta.protocol.ResolverResponseMsg;import net.jxta.resolver.ResolverService;import net.jxta.resolver.QueryHandler;import net.jxta.endpoint.Message;import net.jxta.endpoint.MessageElement;import net.jxta.document.Advertisement;import net.jxta.id.ID;import net.jxta.impl.protocol.ResolverResponse;import net.jxta.impl.protocol.ResolverQuery;/** * This game places players (peers) in a jail (group).  In order to escape * jail, the player must request for the jail token.  Once obtained, * the player may leave, but before leaving, the player must leave the  * token behind with another player. * * After the player leaves, he can not return.  It would be easy to  * restructure this game to allow players to return to the jail, but once * you leave jail, who in their right mind would want to go back? * * Whoever creates the jail automatically creates the only key and places * himself in jail.  All others may join the jail, but they do not have the * key.  The key is not required to enter jail in this game. * * The game demonstrates how messages are passed from peer to peer using * direct connections as well as broadcast methods using the ResolverService. */public class JailGameClient implements Runnable{    public static final String JAIL_GROUP = "JAIL";    public static final String JAIL_GROUP_DESCRIPTION = "Jail description";    public static final String JAIL_KEY_QUERY_HANDLER = "jail_key_query_handler";//JAIL_RESOLVER_HANDLER_NAME = "jail_resolver_handler";    public static final String JAIL_KEY_LOCATOR_HANDLER = "jail_key_locator_handler";    public static final String JAIL_TRANSFER_KEY = "jail_transfer_key";    public static final int JOIN_GAME = 0;    public static final int CREATE_GAME = 1;    private PeerGroup netPeerGroup;    private PeerGroup jailPeerGroup;    private DiscoveryService discoverySvc;    private boolean pipeAdvFound = false;    private int createOrJoin = -1;    private boolean groupFound = false;    private PipeAdvertisement jailUnicastPipeAdv;    private PipeMsgListener unicastListener;    private InputPipe inputUnicastPipe;    private boolean inJail = false;    private boolean hasJailToken = false;    private String jailTokenString;    private Set jailPeerSet = new HashSet();    public JailGameClient(int createOrJoin)    {        this.createOrJoin = createOrJoin;    }    private boolean joinPeerGroup(PeerGroup grp)    {        StructuredDocument creds = null;        try {            AuthenticationCredential authCred =                new AuthenticationCredential(grp, null, creds);            MembershipService membershipSvc = grp.getMembershipService();            Authenticator auth = membershipSvc.apply(authCred);                        if (auth.isReadyForJoin()) {                membershipSvc.join(auth);                this.inJail = true;                return true;            } else {                String errMsg = "Unable to join group:" + grp.getPeerGroupName();                System.out.println(errMsg);                return false;            }        } catch (Exception e) {            String errMsg = "Unable to join group: " + grp.getPeerGroupName();            System.out.println(errMsg);            e.printStackTrace();            return false;        }    }    private boolean joinPeerGroup(PeerGroupAdvertisement adv)    {        try {            return joinPeerGroup(netPeerGroup.newGroup(adv));        } catch (Exception e) {            String errMsg = "Unable to create group from advertisement.";            System.out.println(errMsg);            e.printStackTrace();            return false;        }    }    private PeerGroup createGroup(String name)        throws PeerGroupException, Exception    {        ModuleImplAdvertisement implAdv =            netPeerGroup.getAllPurposePeerGroupImplAdvertisement();        PeerGroup jailGroup =            netPeerGroup.newGroup(null, implAdv, JAIL_GROUP, JAIL_GROUP_DESCRIPTION);        return jailGroup;    }    /**     * Publishes a pipe advertisement for the transfer of the jail token.     */    private void createJailUnicastPipeAdv()        throws IOException    {        PipeAdvertisement pipeAdv = null;        pipeAdv = (PipeAdvertisement) AdvertisementFactory.newAdvertisement(PipeAdvertisement.getAdvertisementType());        pipeAdv.setPipeID(IDFactory.newPipeID(jailPeerGroup.getPeerGroupID()));        pipeAdv.setName(JailGameClient.JAIL_TRANSFER_KEY + ":" + jailPeerGroup.getPeerName());        pipeAdv.setType(PipeService.UnicastType);        this.jailUnicastPipeAdv = pipeAdv;    }    private void publishJailAdv(Advertisement adv, int type)        throws IOException    {        DiscoveryService jailDiscoverySvc = jailPeerGroup.getDiscoveryService();        jailDiscoverySvc.publish(adv, type);        jailDiscoverySvc.remotePublish(adv, type);    }    /**     * Publishes an advertisement locally and remotely with no lifetime.     */    private void publish(Advertisement adv, int type)        throws IOException    {        discoverySvc.publish(adv, type);        discoverySvc.remotePublish(adv, type);    }    /**     * Prints the members of the jail group.     */    private void printPeers()    {        refreshPeerSet();        try {            Thread.sleep(10 * 1000); // may want to sleep longer.        } catch (Exception ignore) { }        Object [] peers = jailPeerSet.toArray();        for (int x = 0 ; x < peers.length ; x++) {            System.out.println("Peer: " + ((PeerAdvertisement)peers[x]).getName());        }    }    /**     * This call is asynchronous and uses a DiscoveryListener to process     * the peer advertisements.     */    private void refreshPeerSet()    {        jailPeerSet.clear();        System.out.println("Searching for peers");        DiscoveryService jailDiscoverySvc = jailPeerGroup.getDiscoveryService();        try {            jailDiscoverySvc.flushAdvertisements(null, DiscoveryService.PEER);            discoverySvc.flushAdvertisements(null, DiscoveryService.PEER);        } catch (IOException io) {            System.out.println("Trouble flushing PEER advertisements");            io.printStackTrace();        }                DiscoveryListener listener = new DiscoveryListener() {                public void discoveryEvent(DiscoveryEvent ev)                {                    DiscoveryResponseMsg res = ev.getResponse();                    String aRes = res.getPeerAdv();                    PeerAdvertisement peerAdv = null;                                        try {                        // create a peer advertisement                        InputStream is = new ByteArrayInputStream( (aRes).getBytes() );                        peerAdv = (PeerAdvertisement)                            AdvertisementFactory.                            newAdvertisement(new MimeMediaType( "text/xml" ), is);                        jailPeerSet.add(peerAdv);                    } catch (Exception e) {                        e.printStackTrace();                    }                }            };        jailDiscoverySvc.getRemoteAdvertisements(null, DiscoveryService.PEER,                                                 null, null, 10, listener);    }    /**     * The discovery listener used needs to be synchronized.  It takes a long time     * to run sometimes.  Furthermore, more than one peer can return the same     * jail group advertisement.     */    private void discoverJailGroup()        throws IOException    {        if (groupFound) {            String msg = "Already found the jail group";            System.out.println(msg);            return;        }        while (!groupFound) {            discoverySvc.getRemoteAdvertisements(null, DiscoveryService.GROUP,                                                  "Name", JailGameClient.JAIL_GROUP,                                                 1, null);            try {                // Wait ten seconds for advertisements to come in                Thread.sleep (10 * 1000);            } catch (Exception ignore) { }            Enumeration enum = discoverySvc.                getLocalAdvertisements(DiscoveryService.GROUP, "Name", JailGameClient.JAIL_GROUP);            // Cycle through all the advertisements cached locally.            while (enum.hasMoreElements()) {

⌨️ 快捷键说明

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