package com.sxc.day;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
/**
* 发送端
* 1.DatagramSocket 指定接口 创建发送端
* 2。准备数据 转成字节数组
* 3。封装成DatagramPacket 包裹 指定目的地
* 4.发送包裹send(DatagramPacket p)
* 5。释放资源
*/
public class UdpServer {
public static void main(String[] args) throws IOException {
System.out.println("发送方启动中");
DatagramSocket client = new DatagramSocket(8888);
String data ="上海尚学堂";
byte[] datas = data.getBytes();
DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress("localhost",9999));
client.send(packet);
client.close();
}
}
package com.sxc.day;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
/**
* 接收端
* 1.DatagramSocket 指定接口 创建接受端
* 2。准备容器 封装成DatagramPacket
* 3.阻塞式接收包裹receive(DatagramPacket p)
* 4.分析数据
* 5。释放资源
*/
public class UdpSend {
public static void main(String[] args) throws IOException {
System.out.println("接收方启动中");
DatagramSocket server = new DatagramSocket(9999);
byte[] container=new byte[1024*60];
DatagramPacket packet = new DatagramPacket(container, 0, container.length);
server.receive(packet);
byte[] datas = packet.getData();
int len=datas.length;
String string = new String(datas,0, datas.length);
System.out.println(string);
server.close();
}
}