【发布时间】:2013-06-12 23:08:10
【问题描述】:
我是网络编程的新手。我想编写一个演示程序来学习如何发送 UDP 广播数据包。这是我写的小demo:
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 没有检测到数据包,但我不知道哪里出了问题。 提前致谢!
【问题讨论】:
-
这里没有广播。客户端和服务器是否在同一主机上运行?
-
出了什么问题?当我运行您的测试时,服务器会很好地接收测试数据包并将它们发送回客户端。也许您的wireshark 正在侦听错误的接口?
-
@EJP
67.194.218.255是广播地址 -
@umlaeute 我在不同的主机上运行它们。也许我使用了错误的广播地址。我在网上搜索了一下,好像Windows7现在不支持255.255.255.255作为广播地址。你能告诉我你是怎么得到你的广播地址的吗?
-
检查您的网络设置:IP地址+网络掩码应该为您提供足够的信息来计算广播地址。在线ipcalc 可能会有所帮助。