import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UdpReceivve {
/**
* {@literal 接收端}
* @author xiaozhazi
* @throws IOException
*
*
*/
public static void main(String[] args) throws IOException {
//1.建立Socket服务,10000:接收端口,与发送端口对应;
DatagramSocket ds=new DatagramSocket(10000);
//定义接收包
byte[] buf =new byte[1024];
DatagramPacket dp= new DatagramPacket(buf, buf.length);
//通过Socket服务 接收数据包
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+"----------ip");
System.out.println(data+"----------data");
System.out.println(port+"----------port");
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class Udpsend {
/**
* @param 上传端
* @author xiaozhazi
* @throws IOException
* @
*/
public static void main(String[] args) throws IOException {
//1.创建udp服务,通过DatagramSocket 对象
DatagramSocket ds= new DatagramSocket();
//2.确定数据,分装成数据包DatagramPacket,10000:发送端口
byte[] buf =null;
buf="小渣子大师来了".getBytes();
DatagramPacket dp =new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.2.36"),10000);
//3.通过Socket服务将数据包发送出去
ds.send(dp);
//4.close Socket
ds.close();
}
}
运行结果如上图;