【Java】UDP发送数据与接收数据
发送
package LearnJava17;
import java.io.IOException;
import java.net.*;
public class SendDemo {
public static void main(String[] args) throws IOException {
// 创建发送端的Socket对象
DatagramSocket ds = new DatagramSocket();
// 创建数据并打包
byte[] bys = "Hello,DUP".getBytes();
// int length = bys.length;
// InetAddress address = InetAddress.getByName("127.0.0.1");
// int port = 10086;
// DatagramPacket dp = new DatagramPacket(bys, length, address, port);
DatagramPacket dp = new DatagramPacket(bys, bys.length, InetAddress.getByName("127.0.0.1"), 10086);
// 发送数据
ds.send(dp);
// 关闭发送端
ds.close();
}
}
接收
package LearnJava17;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class ReceiveDemo {
public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket(10086);
// 创建一个数据包,用于接收数据
byte[] bys=new byte[1024];
DatagramPacket dp=new DatagramPacket(bys,bys.length);
// 接收数据
ds.receive(dp);
// 解析数据包
// byte[] datas = dp.getData();
// 返回数据长度
// int len = dp.getLength();
// String dataString = new String(datas,0,len);
// System.out.println("数据是:"+dataString);
System.out.println("数据是:"+new String(dp.getData(),0, dp.getLength()));
ds.close();
}
}
本文来自博客园,作者:木子欢儿,转载请注明原文链接:https://www.cnblogs.com/HGNET/p/16207231.html