public class UdpRece {
public static void main(String[] args) throws Exception{
//1.定义Socket
DatagramSocket ds = new DatagramSocket(10088);
//2.创建数据包
byte[] buf = new byte[1024];
DatagramPacket dp =
new DatagramPacket(buf,buf.length);
//3.接受数据
ds.receive(dp);
//解析数据
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData(),0,dp.getLength());
int port = dp.getPort();
System.out.println(ip);
System.out.println(data);
System.out.println(port);
ds.close();
}
}
public class UdpSend {
public static void main(String[] args)throws Exception {
//1,创建udp服务。通过DatagramSocket对象。
DatagramSocket ds = new DatagramSocket(8888);
//2,确定数据,并封装成数据包。DatagramPacket(byte[] buf, int length, InetAddress address, int port)
/*InetAddress ia = InetAddress.getLocalHost();
System.out.println(ia);
InetAddress ia1 = InetAddress.getByName("SKY-20170715YUU");
System.out.println(ia1.getHostAddress());*/
byte[] buf = "udp ge men lai le ".getBytes();
DatagramPacket dp =
new DatagramPacket(buf,buf.length,InetAddress.getByName("10.0.107.243"),10088);
//3,通过socket服务,将已有的数据包发送出去。通过send方法。
ds.send(dp);
//4,关闭资源。
ds.close();
}
}