UDP广播客户端和服务器没有互相检测

时间:2016-08-28 00:01:44

标签: java android udp datagram udpclient

我目前正在尝试遵循Michiel De Mey在检测LAN IP时创建的示例代码。 请参阅其代码的链接:https://demey.io/network-discovery-using-udp-broadcast/

无论如何,我试着跟着它,我基本上得到了他得到的东西。当我在我的电脑上运行服务器和客户端时,它工作,但当我从我的PC运行服务器,从我的Android应用程序运行客户端时,客户端没有注册来自服务器的回复,或者甚至没有得到那里的一切。我真的很不确定。

我只是觉得可能是因为我的固定电脑通过电缆连接到网络,而目前运行Android模拟器的笔记本电脑通过wifi连接到网络,路由器将两者分开。 / p>

为什么它无法通过我的局域网运行? (我正确连接,并且我在android中将StrictMode ThreadPolicy设置为permitAll),所以我知道这不是问题。

提前致谢!

对于服务器端,我有这段代码:

public class DiscoveryThread implements Runnable {

    public static void main(String[] args){
        Thread discoveryThread = new Thread(DiscoveryThread.getInstance());  
        discoveryThread.start(); 
    }

      DatagramSocket socket;

      @Override
      public void run() {
        try {
          //Keep a socket open to listen to all the UDP trafic that is destined for this port
          socket = new DatagramSocket(6789, 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_FUIFSERVER_REQUEST")) {
              byte[] sendData = "DISCOVER_FUIFSERVER_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());
            }
          }
        } catch (IOException ex) {
          Logger.getLogger(DiscoveryThread.class.getName()).log(Level.SEVERE, null, ex);
        }
      }

      public static DiscoveryThread getInstance() {
            return DiscoveryThreadHolder.INSTANCE;
          }

          private static class DiscoveryThreadHolder {

            private static final DiscoveryThread INSTANCE = new DiscoveryThread();
          }
    }

客户方:

public class UDPClient {
    DatagramSocket c = null;

    public void connect(){
        try{
        c = new DatagramSocket();
        c.setBroadcast(true);
        byte[] sendData = "DISCOVER_FUIFSERVER_REQUEST".getBytes();

        try{

            byte[] buf = new byte[256];
            InetAddress ip = InetAddress.getByName("255.255.255.255");
            DatagramPacket packet = new DatagramPacket(sendData,sendData.length,ip,6789);
            c.send(packet);
            System.out.println(getClass().getName() + ": Request packet sent to: 255.255.255.255 (DEFAULT)");

        }catch(IOException e){
            e.printStackTrace();
        }

        // Broadcast the message over all the network interfaces
        Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
          NetworkInterface networkInterface = (NetworkInterface) interfaces.nextElement();

          if (networkInterface.isLoopback() || !networkInterface.isUp()) {
            continue; // Don't want to broadcast to the loopback interface
          }

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

            // Send the broadcast package!
            try {
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 6789);
              c.send(sendPacket);
            } catch (Exception e) {
            }

            System.out.println(getClass().getName() + ": Request packet sent to: " + broadcast.getHostAddress() + "; Interface: " + networkInterface.getDisplayName());
          }
        }

        System.out.println(getClass().getName() + ": Done looping over all network interfaces. Now waiting for a reply!");

        //Wait for a response
        byte[] recvBuf = new byte[15000];
        DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
        c.receive(receivePacket);

        //We have a response
        System.out.println(getClass().getName() + ": Broadcast response from server: " + receivePacket.getAddress().getHostAddress());

        //Check if the message is correct
        String message = new String(receivePacket.getData()).trim();
        if (message.equals("DISCOVER_FUIFSERVER_RESPONSE")) {
          //DO SOMETHING WITH THE SERVER'S IP (for example, store it in your controller)
            System.out.println("Server's IP: "+receivePacket.getAddress());
        }

        //Close the port!
        c.close();
      } catch (IOException ex) {
       // Logger.getLogger(LoginWindow.class.getName()).log(Level.SEVERE, null, ex);
    }
    }

}

0 个答案:

没有答案