Java 如何在JXTA-JXSE 2.6中发现对等点并发送消息?

Java 如何在JXTA-JXSE 2.6中发现对等点并发送消息?,java,p2p,jxta,Java,P2p,Jxta,使用来自的JXTA2.6,我想创建一个可以在一个或多个主机上运行多个对等点的应用程序。对等方应该能够在一个组中找到彼此,发送直接消息以及传播消息 一个简单的hello world类型的应用程序会是什么样的,以满足这些需求 我创建这个问题的目的是提供一个类似于教程的答案,两个月前,当我开始为一个uni项目研究JXTA时,我非常努力地寻找这个答案。请随意添加您自己的答案或改进我的答案。我将等待几天,然后接受最好的一个。JXTA 2.6对等发现和管道消息传递简介 我希望2个月前有一本指南=) 在大学课

使用来自的JXTA2.6,我想创建一个可以在一个或多个主机上运行多个对等点的应用程序。对等方应该能够在一个组中找到彼此,发送直接消息以及传播消息

一个简单的hello world类型的应用程序会是什么样的,以满足这些需求


我创建这个问题的目的是提供一个类似于教程的答案,两个月前,当我开始为一个uni项目研究JXTA时,我非常努力地寻找这个答案。请随意添加您自己的答案或改进我的答案。我将等待几天,然后接受最好的一个。

JXTA 2.6对等发现和管道消息传递简介

我希望2个月前有一本指南=)

在大学课程建设中花了很多时间之后 一个JXTA p2p应用程序,我感觉到了很多挫折和挫折 我所经历的困惑本可以用一个好的方法来避免 起点

您需要的jar文件可以在这里找到:

将它们放入您的project/lib中,打开eclipse,创建一个新的项目“Yourproject”,它应该会整理出来 为您导入库

你很快就会意识到网络上几乎所有的信息都过时了,非常过时。 您还将遇到许多非常混乱的错误消息,大多数错误消息可以通过以下方法避免: 检查一下这个清单

  • 您的防火墙是否已关闭或至少已为您使用的端口打开? 您可以使用Fedora下的“sudo service iptables stop”禁用iptables

  • 检查拼写!在加入组或尝试发送组名拼写错误或未使用 在寻找同龄人和服务或打开管道时,完全相同的广告将导致非常混乱的消息。 当我发现组名为“Net info”和“Net_info”时,我正在试图找出管道连接超时的原因

  • 您正在使用JXTA主目录吗?您在同一台计算机上运行的每台对等计算机一个

  • 您真的使用唯一的对等id吗?提供给IDFactory的种子需要足够长,否则您将得到重复的种子

  • 关闭SELinux。我在开发过程中关闭了SELinux,但可以想象它会导致错误

虽然将所有字段组合在一起是很常见的,但我会在介绍它们的同时说明需要它们的地方

注意:这在2.7中不起作用。我认为PSE成员资格存在一些问题

public class Hello implements DiscoveryListener, PipeMsgListener {

    // When developing you should handle these exceptions, I don't to lessen the clutter of start()
    public static void main(String[] args) throws PeerGroupException, IOException {

        // JXTA logs a lot, you can configure it setting level here
        Logger.getLogger("net.jxta").setLevel(Level.ALL);


        // Randomize a port to use with a number over 1000 (for non root on unix)
        // JXTA uses TCP for incoming connections which will conflict if more than
        // one Hello runs at the same time on one computer.
        int port = 9000 + new Random().nextInt(100);

        Hello hello = new Hello(port);
        hello.start(); 
        hello.fetch_advertisements();
    }


    private String peer_name;
    private PeerID peer_id;
    private File conf;
    private NetworkManager manager;

    public Hello(int port) {
        // Add a random number to make it easier to identify by name, will also make sure the ID is unique 
        peer_name = "Peer " + new Random().nextInt(1000000); 

        // This is what you will be looking for in Wireshark instead of an IP, hint: filter by "jxta"
        peer_id = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID, peer_name.getBytes());

        // Here the local peer cache will be saved, if you have multiple peers this must be unique
        conf = new File("." + System.getProperty("file.separator") + peer_name);

        // Most documentation you will find use a deprecated network manager setup, use this one instead
        // ADHOC is usually a good starting point, other alternatives include Edge and Rendezvous
        try {
            manager = new NetworkManager(
                    NetworkManager.ConfigMode.ADHOC,
                    peer_name, conf.toURI());
        }
        catch (IOException e) {
            // Will be thrown if you specify an invalid directory in conf
            e.printStackTrace();
        }

        NetworkConfigurator configurator;
        try {
            // Settings Configuration
            configurator = manager.getConfigurator();
            configurator.setTcpPort(port);
            configurator.setTcpEnabled(true);
            configurator.setTcpIncoming(true);
            configurator.setTcpOutgoing(true);
            configurator.setUseMulticast(true);
            configurator.setPeerID(peer_id);
        } 
        catch (IOException e) {
            // Never caught this one but let me know if you do =)
            e.printStackTrace();
        }
    }

    private static final String subgroup_name = "Make sure this is spelled the same everywhere";
    private static final String subgroup_desc = "...";
    private static final PeerGroupID subgroup_id = IDFactory.newPeerGroupID(PeerGroupID.defaultNetPeerGroupID, subgroup_name.getBytes());

    private static final String unicast_name = "This must be spelled the same too";
    private static final String multicast_name = "Or else you will get the wrong PipeID";

    private static final String service_name = "And dont forget it like i did a million times";

    private PeerGroup subgroup;
    private PipeService pipe_service;
    private PipeID unicast_id;
    private PipeID multicast_id;
    private PipeID service_id;
    private DiscoveryService discovery;
    private ModuleSpecAdvertisement mdadv;

    public void start() throws PeerGroupException, IOException {
        // Launch the missiles, if you have logging on and see no exceptions
        // after this is ran, then you probably have at least the jars setup correctly.
        PeerGroup net_group = manager.startNetwork();

        // Connect to our subgroup (all groups are subgroups of Netgroup)
        // If the group does not exist, it will be automatically created
        // Note this is suggested deprecated, not sure what the better way is
        ModuleImplAdvertisement mAdv = null;
        try {
            mAdv = net_group.getAllPurposePeerGroupImplAdvertisement();
        } catch (Exception ex) {
            System.err.println(ex.toString());
        }
        subgroup = net_group.newGroup(subgroup_id, mAdv, subgroup_name, subgroup_desc);

        // A simple check to see if connecting to the group worked
        if (Module.START_OK != subgroup.startApp(new String[0]))
            System.err.println("Cannot start child peergroup");

        // We will spice things up to a more interesting level by sending unicast and multicast messages
        // In order to be able to do that we will create to listeners that will listen for
        // unicast and multicast advertisements respectively. All messages will be handled by Hello in the
        // pipeMsgEvent method. 

        unicast_id = IDFactory.newPipeID(subgroup.getPeerGroupID(), unicast_name.getBytes());
        multicast_id = IDFactory.newPipeID(subgroup.getPeerGroupID(), multicast_name.getBytes());

        pipe_service = subgroup.getPipeService();
        pipe_service.createInputPipe(get_advertisement(unicast_id, false), this);
        pipe_service.createInputPipe(get_advertisement(multicast_id, true), this);

        // In order to for other peers to find this one (and say hello) we will
        // advertise a Hello Service.
        discovery = subgroup.getDiscoveryService();
        discovery.addDiscoveryListener(this);        

        ModuleClassAdvertisement mcadv = (ModuleClassAdvertisement)
        AdvertisementFactory.newAdvertisement(ModuleClassAdvertisement.getAdvertisementType());

        mcadv.setName("STACK-OVERFLOW:HELLO");
        mcadv.setDescription("Tutorial example to use JXTA module advertisement Framework");

        ModuleClassID mcID = IDFactory.newModuleClassID();

        mcadv.setModuleClassID(mcID);

        // Let the group know of this service "module" / collection
        discovery.publish(mcadv);
        discovery.remotePublish(mcadv);

        mdadv = (ModuleSpecAdvertisement)
                AdvertisementFactory.newAdvertisement(ModuleSpecAdvertisement.getAdvertisementType());
        mdadv.setName("STACK-OVERFLOW:HELLO");
        mdadv.setVersion("Version 1.0");
        mdadv.setCreator("sun.com");
        mdadv.setModuleSpecID(IDFactory.newModuleSpecID(mcID));
        mdadv.setSpecURI("http://www.jxta.org/Ex1");

        service_id = IDFactory.newPipeID(subgroup.getPeerGroupID(), service_name.getBytes());
        PipeAdvertisement pipeadv = get_advertisement(service_id, false);
        mdadv.setPipeAdvertisement(pipeadv);

        // Let the group know of the service
        discovery.publish(mdadv);
        discovery.remotePublish(mdadv);

        // Start listening for discovery events, received by the discoveryEvent method
        pipe_service.createInputPipe(pipeadv, this);
    }

    private static PipeAdvertisement get_advertisement(PipeID id, boolean is_multicast) {
        PipeAdvertisement adv = (PipeAdvertisement )AdvertisementFactory.
            newAdvertisement(PipeAdvertisement.getAdvertisementType());
        adv.setPipeID(id);
        if (is_multicast)
            adv.setType(PipeService.PropagateType); 
        else 
            adv.setType(PipeService.UnicastType); 
        adv.setName("This however");
        adv.setDescription("does not really matter");
        return adv;
    }

    @Override public void discoveryEvent(DiscoveryEvent event) {
        // Found another peer! Let's say hello shall we!
        // Reformatting to create a real peer id string
        String found_peer_id = "urn:jxta:" + event.getSource().toString().substring(7);
        send_to_peer("Hello", found_peer_id);
    }


    private void send_to_peer(String message, String found_peer_id) {
        // This is where having the same ID is important or else we wont be
        // able to open a pipe and send messages
        PipeAdvertisement adv = get_advertisement(unicast_id, false);

        // Send message to all peers in "ps", just one in our case
        Set<PeerID> ps = new HashSet<PeerID>();
        try {
            ps.add((PeerID)IDFactory.fromURI(new URI(found_peer_id)));
        } 
        catch (URISyntaxException e) {
            // The JXTA peer ids need to be formatted as proper urns
            e.printStackTrace();
        }

        // A pipe we can use to send messages with
        OutputPipe sender = null;
        try {
            sender = pipe_service.createOutputPipe(adv, ps, 10000);
        } 
        catch (IOException e) {
            // Thrown if there was an error opening the connection, check firewall settings
            e.printStackTrace();
        }

        Message msg = new Message();
        MessageElement fromElem = null;
        MessageElement msgElem = null;
        try {
            fromElem = new ByteArrayMessageElement("From", null, peer_id.toString().getBytes("ISO-8859-1"), null);
            msgElem = new ByteArrayMessageElement("Msg", null, message.getBytes("ISO-8859-1"), null);
        } catch (UnsupportedEncodingException e) {
            // Yepp, you want to spell ISO-8859-1 correctly
            e.printStackTrace();
        }


         msg.addMessageElement(fromElem);
         msg.addMessageElement(msgElem);

         try {
            sender.send(msg);
        } catch (IOException e) {
            // Check, firewall, settings.
            e.printStackTrace();
        }
    }

    @Override public void pipeMsgEvent(PipeMsgEvent event) {
        // Someone is sending us a message!
        try {
            Message msg = event.getMessage();
            byte[] msgBytes = msg.getMessageElement("Msg").getBytes(true);  
            byte[] fromBytes = msg.getMessageElement("From").getBytes(true); 
            String from = new String(fromBytes);
            String message = new String(msgBytes);
            System.out.println(message + " says " + from);
        }
        catch (Exception e) {
            // You will notice that JXTA is not very specific with exceptions...
            e.printStackTrace();
        }
    }

    /**
     * We will not find anyone if we are not regularly looking
     */
    private void fetch_advertisements() {
      new Thread("fetch advertisements thread") {
         public void run() {
            while(true) {
                discovery.getRemoteAdvertisements(null, DiscoveryService.ADV, "Name", "STACK-OVERFLOW:HELLO", 1, null);
                try {
                    sleep(10000);

                }
                catch(InterruptedException e) {} 
            }
         }
      }.start();
   }
}
public类Hello实现DiscoveryListener、PipeMsgListener{
//在开发时,您应该处理这些异常,我不想减少start()的混乱
公共静态void main(字符串[]args)引发PeerGroupException、IOException{
//JXTA日志很多,您可以在这里配置它的设置级别
Logger.getLogger(“net.jxta”).setLevel(Level.ALL);
//随机化一个端口以使用超过1000的数字(对于unix上的非root用户)
//JXTA对传入连接使用TCP,如果超过
//一个Hello同时在一台计算机上运行。
int port=9000+新随机数().nextInt(100);
Hello Hello=新Hello(端口);
您好,开始();
你好,去拿广告;
}
私有字符串peer_name;
私有PeerID;
私有文件配置;
专用网络管理器;
公共Hello(int端口){
//添加一个随机数,以便于通过名称进行识别,还将确保ID是唯一的
peer_name=“peer”+new Random().nextInt(1000000);
//这是您将在Wireshark中查找的内容,而不是IP,提示:按“jxta”筛选
peer_id=IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID,peer_name.getBytes());
//此处将保存本地对等缓存,如果有多个对等缓存,则必须是唯一的
conf=新文件(“.”+System.getProperty(“File.separator”)+对等方名称);
//您将发现的大多数文档都使用不推荐的network manager设置,请改用此设置
//临时会议通常是一个很好的起点,其他选择包括边缘和会合
试一试{
manager=新的网络管理器(
NetworkManager.ConfigMode.ADHOC,
peer_name,conf.toURI());
}
捕获(IOE异常){
//如果在conf中指定无效目录,将引发
e、 printStackTrace();
}
网络配置器;
试一试{
//设置配置
configurator=manager.getConfigurator();
configurator.SettCPort(端口);
configurator.setTcpEnabled(true);
configurator.setTcpIncoming(true);
configurator.setTcpOutgoing(true);
configurator.setUseMulticast(true);
configurator.setPeerID(对等id);
} 
捕获(IOE异常){
//从未抓到过这个,但如果抓到了,请告诉我=)
e、 printStackTrace();
}
}
private static final String subgroup_name=“确保每个地方的拼写都相同”;
私有静态最终字符串子组_desc=“…”;
私有静态最终PeerGroupID子组_id=IDFactory.newPeerGroupID(PeerGroupID.defaultNetPeerGroupID,子组_name.getBytes());
private static final String unicast_name=“这也必须拼写相同”;
private static final String multicast_name=“否则您将得到错误的管道ID”;
private static final String service_name=“别忘了,就像我做了一百万次一样”;
私有PeerGroup子组;
私人管道服务;
专用管道单播id;
私有管道多播;
专用管道服务\u id;
私人发现服务发现;
私有模块mdadv;
public void start()引发PeerGroupException,IOEXE