图片来自网络
【发送端】
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;
//发送端
public class MySend {
public static void main(String[] args) {
DatagramSocket send = null;
try {
//创建DatagramSocket对象
send = new DatagramSocket();
//创建发送的数据
byte[] send_data = ("\n\t"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+",Send-发送测试").getBytes();
//创建DatagramSocket对象
DatagramPacket dp = new DatagramPacket(send_data, send_data.length, InetAddress.getByName("127.0.0.1"), 1515);
//发送数据包
send.send(dp);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭资源
send.close();
}
}
}
【接收端】
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
//接收端
public class MyReceive {
public static void main(String[] args) {
DatagramSocket receive = null;
try {
//创建监听1515端口的DatagramSocket对象
receive = new DatagramSocket(1515);
//创建存储数据的容器
byte[] buf = new byte[1024];
//创建DatagramPacket对象
DatagramPacket dp = new DatagramPacket(buf, buf.length);
while(true) {
//接受数据包
receive.receive(dp);
//打印数据
String data = new String(dp.getData());
System.out.println("来自发送端:"+data);
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭资源
receive.close();
}
}
}