/*
* 发送端
*/
public void send() throws Exception {
System.out.println("send..............");
// 得到目标机器的地址实例
InetAddress target = InetAddress.getByName("localhost");
// 从8888端口发送数据报
DatagramSocket ds = new DatagramSocket(8888);
String hello = "Hello, I am come in!";
// 将数据转换成Byte类型
byte [] buf = hello.getBytes();
// 将BUF缓冲区中的数据打包,目标端口为8889
DatagramPacket op = new DatagramPacket(buf, buf.length, target, 8889);
// 发送
ds.send(op);
ds.close();
System.out.println("send end." + target.getHostAddress());
}
/*
* 接收端
*/
public void receive() throws Exception {
System.out.println("receive........");
byte [] buf = new byte [1000];
// 监视8889端口
DatagramSocket ds = new DatagramSocket(8889);
// 创建接收数据报的实例
DatagramPacket ip = new DatagramPacket(buf, buf.length);
while (true ) {
// 将收到的数据报装入IP中
ds.receive(ip);
System.out.println(new String(buf));
}
}