- UDP编程
- 概念
- 举例
- 项目开发流程:
- 通讯项目
UDP编程
概念
- UDP编程通过DatagramSocket和Datagrampacket来完成,没有客户端和服务器的概念,而是演变成数据的接收端和发送端
- Datagrampacket叫数据报/数据包,发送数据时把数据封装到Datagrampacket对象中,叫装包。当接收到Datagrampacket对象,需要进行拆包,取出对象。
- 接收数据和发送数据通过DatagramSocket对象来完成
举例
udp编程就是先new一个Datagrampacket(可以用来接收或发送),然后new DatagramSocket,通过send(Datagrampacket)发送,receive(Datagrampacket)接收到Datagrampacket对象中
sender
byte[] bytes = "hello,receiver".getBytes();
DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, InetAddress.getByName("192.168.230.48"), 9999);
DatagramSocket datagramSocket = new DatagramSocket(8888);
datagramSocket.send(datagramPacket);
byte[] bytes2 = new byte[1024];
DatagramPacket datagramPacket1 = new DatagramPacket(bytes2, bytes2.length);
datagramSocket.receive(datagramPacket1);
int length = datagramPacket1.getLength();
byte[] data = datagramPacket1.getData();
String s = new String(data, 0, length);
System.out.println(s);
datagramSocket.close();
receiver
byte[] bytes = new byte[1024];
DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
DatagramSocket datagramSocket = new DatagramSocket(9999);
datagramSocket.receive(datagramPacket);
int length = datagramPacket.getLength();
byte[] data = datagramPacket.getData();
System.out.println(new String(data,0,length));
byte[] bytes2 = "hello,sender".getBytes();
DatagramPacket datagramPacket2 = new DatagramPacket(bytes2, bytes2.length, InetAddress.getByName("192.168.230.48"), 8888);
datagramSocket.send(datagramPacket2);
datagramSocket.close();