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的檢測數據包,但我想不通的地方是錯誤的。 在此先感謝!
這裏沒有廣播。客戶端和服務器是否在同一主機上運行? – EJP
出了什麼問題?當我運行你的測試時,服務器收到測試包就好了,並將它們發送回客戶端。也許你的wireshark聽錯了界面? –
@EJP'67.194.218.255'是一個廣播地址 –