UDP通信
程序员文章站
2022-07-01 17:18:40
...
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketException;
public class DatagramDemo {
public static void main(String[] args) {
try {
//1、创建客户端口
DatagramSocket server=new DatagramSocket(6666);
//2、准备数据
String msg="传输数据";
byte[] data=msg.getBytes();
//3、打包数据、发送位置
DatagramPacket packet =new DatagramPacket(data, data.length,new InetSocketAddress("localhost", 8989));
//4、发送
server.send(packet);
server.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class DatagramScoketDemo {
public static void main(String[] args) {
try {
//1、创建服务端端口
DatagramSocket server=new DatagramSocket(8989);
//2、准备接受容器
byte[] datas=new byte[1024];
//3、封装成包
DatagramPacket packet=new DatagramPacket(datas, datas.length);
//4、接受数据
server.receive(packet);
//5、分析数据
byte[] data=packet.getData();
int len=packet.getLength();
System.out.println(new String(data,0,len));
//关闭
server.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
上一篇: TCP协议
下一篇: 题410. 分割数组的最大值