import java.net.*;
//发送端
class L
{
public static void main(String args[]) throws Exception
{
DatagramSocket ds=new DatagramSocket(888);
byte[] buf="I love you".getBytes();
DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.101"),10000);
ds.send(dp);
ds.close();
}
}
//接收端
class L1
{
public static void main(String args[]) throws Exception
{
DatagramSocket ds=new DatagramSocket(10000);
byte[] buf=new byte[1024];
DatagramPacket dp1=new DatagramPacket(buf,buf.length);
ds.receive(dp1);//阻塞式方法,read()也是阻塞式方法。
String add=dp1.getAddress().getHostAddress();
String name=dp1.getAddress().getHostName();
System.out.println(add);
System.out.println(name);
String all=new String(dp1.getData(),0,dp1.getLength());
int port=dp1.getPort();
System.out.println(all);
System.out.println(port);
ds.close();
}
}