2013-06-12 30 views
0

我是網絡編程的新手。我想寫一個演示程序來學習如何發送UDP廣播數據包。這裏是小的演示中,我寫道:Java UDP廣播數據包無法檢測

public class DatagramClient 
{ 
    private final static int PACKETSIZE = 100 ; 

    public static void main(String args[]) 
    { 

     DatagramSocket socket = null ; 

     try 
     { 
     // Convert the arguments first, to ensure that they are valid 
     InetAddress host = InetAddress.getByName("67.194.218.255") ; 
     int port   = 34567;//Integer.parseInt(args[1]) ; 

     // Construct the socket 
     socket = new DatagramSocket() ; 

     // Construct the datagram packet 
     byte [] data = "Hello Server".getBytes() ; 
     DatagramPacket packet = new DatagramPacket(data, data.length, host, port) ; 

     // Send it 
     socket.send(packet) ; 

     // Set a receive timeout, 2000 milliseconds 
     socket.setSoTimeout(2000) ; 

     // Prepare the packet for receive 
     packet.setData(new byte[PACKETSIZE]) ; 

     // Wait for a response from the server 
     socket.receive(packet) ; 

     // Print the response 
     System.out.println(new String(packet.getData())) ; 

     } 
     catch(Exception e) 
     { 
     System.out.println(e) ; 
     } 
     finally 
     { 
     if(socket != null) 
      socket.close() ; 
     } 
    } 
} 



public class DatagramServer 
{ 

    private final static int PACKETSIZE = 100 ; 

    public static void main(String args[]) 
    { 
     try 
     { 

     // Convert the argument to ensure that is it valid 

     int port = 34567; 

     // Construct the socket 
     DatagramSocket socket = new DatagramSocket(port) ; 
     socket.setBroadcast(true); 

     System.out.println("The server is ready...") ; 


     for(;;) 
     { 
      // Create a packet 
      DatagramPacket packet = new DatagramPacket(new byte[PACKETSIZE], PACKETSIZE) ; 

      // Receive a packet (blocking) 
      socket.receive(packet) ; 

      // Print the packet 
      System.out.println(packet.getAddress() + " " + packet.getPort() + ": " + new String(packet.getData())) ; 

      // Return the packet to the sender 
      socket.send(packet) ; 
     } 
    } 
    catch(Exception e) 
    { 
     System.out.println(e) ; 
    } 
    } 
} 

沒有通過Wireshark的檢測數據包,但我想不通的地方是錯誤的。 在此先感謝!

+0

這裏沒有廣播。客戶端和服務器是否在同一主機上運行? – EJP

+0

出了什麼問題?當我運行你的測試時,服務器收到測試包就好了,並將它們發送回客戶端。也許你的wireshark聽錯了界面? –

+0

@EJP'67.194.218.255'是一個廣播地址 –

回答

0

您的目標地址67.194.218.25567.194.218/24網絡的廣播地址,但您的實際網絡設置可能不同,因此您必須使用正確的廣播地址。

最簡單的解決方案是使用最廣泛的廣播地址255.255.255.255

如果這不起作用,你可能要到目的地址縮小到您的實際網絡。使用你的IP地址和你的網絡掩碼應該允許你通過對IP地址和反向網絡掩碼進行或運算來計算廣播地址。 IP=192.168.1.7; mask=255.255.255.0 - >broadcast = 192.168.1.7 || 0.0.0.255 = 192.168.1.255

爲了簡單起見,您還可以使用ipcalc(網絡計算器);甚至有一個online version