LAN上的Peer to Peer发现

时间:2015-01-05 20:57:41

标签: java networking network-programming udp lan

所以,正如标题可能暗示我在Java项目中遇到了一些麻烦。我想做的是:

  • 我有两台运行应用程序X的计算机
  • 还有另外三台运行应用程序Y的计算机

我需要做的是在X和Y之间建立连接。例如,有人使用运行X的计算机,在discovrey进程之后,他们将返回运行Y app的计算机列表,并且他们的IP,反之亦然。

我使用UDP广播完成了这项工作,但有时会失败。计算机通过WiFi连接,所以基本上通过路由器。在很多情况下,任何X计算机都可以通过我的UDP发现方法看到Y计算机,但有时候不会,除非我手动指向IP,有时甚至不是。

以下是用于发现侦听特定端口的服务器的代码:

public static ArrayList<InetAddress> searchComputer() {
    ArrayList<InetAddress> targets = new ArrayList<InetAddress>();
    try {
        c = new DatagramSocket();
        c.setBroadcast(true);

        byte[] sendData = "DISCOVER_PC_SERVER_REQUEST".getBytes();
        try {
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName("255.255.255.255"), 2005);
            c.send(sendPacket);
        } catch (Exception e) {}
        Enumeration interfaces = NetworkInterface.getNetworkInterfaces();

        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = (NetworkInterface) interfaces.nextElement();

            if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                continue; 
            }

            for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                InetAddress broadcast = interfaceAddress.getBroadcast();
                if (broadcast == null) {
                    continue;
                }

                try {
                    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 8888);
                    c.send(sendPacket);
                } catch (Exception e) { }
            }
        }
        byte[] recvBuf = new byte[15000];
        DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
        if (useInstant) {
            c.setSoTimeout(500);
        }
        else {
            c.setSoTimeout(4000); //EXECUTE THE WHILE FOR 4 SECONDS, THEN RETURN WHATEVER THE RESULTS ARE.
        }
        while (true) {
            c.receive(receivePacket);
            String message = new String(receivePacket.getData()).trim();
            if (message.equals("DISCOVER_PC_SERVER_RESPONSE")) {
//              return receivePacket.getAddress();
                targets.add(receivePacket.getAddress());
            }
        }
//      c.close();
    } catch (IOException ex){}
    return targets;
}

这是我的&#34;服务器&#34;:

private void start_Discovery() throws Exception {
    //Keep a socket open to listen to all the UDP trafic that is destined for this port
    socket = new DatagramSocket(2005, InetAddress.getByName("0.0.0.0"));
    socket.setBroadcast(true);

    while (true) {
//      System.out.println(getClass().getName() + ">>>Ready to receive broadcast packets!");

        //Receive a packet
        byte[] recvBuf = new byte[15000];
        DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
        socket.receive(packet);

        //Packet received
//      System.out.println(getClass().getName() + ">>>Discovery packet received from: " + packet.getAddress().getHostAddress());
//      System.out.println(getClass().getName() + ">>>Packet received; data: " + new String(packet.getData()));

        //See if the packet holds the right command (message)
        String message = new String(packet.getData()).trim();
        if (message.equals("DISCOVER_ANDROID_SERVER_REQUEST")) {
            byte[] sendData = "DISCOVER_ANDROID_SERVER_RESPONSE".getBytes();

            //Send a response
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, packet.getAddress(), packet.getPort());
            socket.send(sendPacket);

//          System.out.println(getClass().getName() + ">>>Sent packet to: " + sendPacket.getAddress().getHostAddress());
        }
    }
}

为什么有时他们无法看到对方,即使他们连接到同一个路由器? 额外:是否有特殊情况,X计算机通过LAN连接,Y计算机通过WiFi连接?

1 个答案:

答案 0 :(得分:1)

  

为什么有时他们无法看到对方,即使他们已经连接到了   同一个路由器?

因为广播是使用无连接协议的UDP服务完成的。使用UDP,您只需将数据包(数据报)发送到网络上的某个IP地址。您无法保证数据会到达。

  

是否有特殊情况,X计算机通过LAN连接,并且   通过WiFi的Y?

甚至,X cmputers通过LAN连接,而Y通过WiFi连接,它们都属于同一个路由器网络。因此,网络发现和网络服务将可用。这没有任何问题。这是公平的,与你所拥有的情况没有什么不同!