java中UDP的基本步骤
package Net;
//发送端
//同一个协议下 端口不允许冲突
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
public class TsetUDPClicent {
public static void main(String[] args) throws Exception {
System.out.println(“发送端启动中”);
//1.使用DatagramSocket指定端口 创建发送端
DatagramSocket client = new DatagramSocket(9999);
//2.准备数据 一定转成成字节数组
String s = “你好”;
byte[] b = s.getBytes();
//3.封装成DatagramPacket包裹 需要指定目的地(端口号与接收端一致)
DatagramPacket packet = new DatagramPacket(b,0,b.length,new InetSocketAddress(“localhost”,6666));
//4.发送包裹send(DatagramPacket)
client.send(packet);
//5.释放资源
client.close();
}
}
package Net;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
//接收端
public class TestUDPServer {
public static void main(String[] args) throws Exception {
System.out.println(“接收端启动中”);
//1.使用DatagramSocket指定端口 创建接收端
DatagramSocket server = new DatagramSocket(6666);
//2.准备容器 一定转成成字节数组
byte[] b = new byte[1024*60];
DatagramPacket packet = new DatagramPacket(b,0,b.length);
//3.阻塞式接收包裹包裹receive(DatagramPacket)
server.receive( packet);
//4.分析数据
byte[] b1 = packet.getData();
int len = packet.getLength();
System.out.println(new String(b1,0,len));
//5.释放资源
server.close();
}
}