发送数据
java
public class sendmessage {
public static void main (String[] args) throws IOException {
DatagramSocket ds=new DatagramSocket();
//打包数据开始
String s="hello world";
byte[] b=s.getBytes();
//获取InetAddress的对象
InetAddress address=InetAddress.getByName("127.0.0.1");
//端口号
int port=10086;
//打包数据结束
DatagramPacket dp=new DatagramPacket(b,b.length,address,port);
//发送数据
ds.send(dp);
//释放数据
ds.close();
}
}
接受数据
java
public class receivemessage {
public static void main (String[] args) throws IOException {
//接受的时候一定要绑定端口
//绑定的端口一定要和发送的端口保持一致
DatagramSocket ds=new DatagramSocket(10086);
//接受数据包
byte[] b=new byte[1024];
DatagramPacket dp=new DatagramPacket(b,b.length);
ds.receive(dp);
//解析数据包
//获取数据
byte[] result=dp.getData();
int len=dp.getLength();
//获取发送方的地址
InetAddress address=dp.getAddress();
//获取发送方的发送端口
int port=dp.getPort();
System.out.println(new String(result,0,len));
System.out.println("发送方的地址"+address+"发送方的发送端口"+port);
ds.close();
}
}
要先运行接收端再运行发送端,否则无法收到数据
初学者,见解不足,如有错误请指出