一、创建UDP传输的发送端
1、建立UDP的Socket服务;
2、将要发送的数据封装到数据包中;
3、通过UDP的Socket服务将数据包发送出去;
4、关闭Socket服务。
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPSend {
public static void main(String[] args) throws IOException {
System.out.println("发送端启动......");
DatagramSocket ds = new DatagramSocket();
String str = "UDP传输演示:I'm coming!";
byte[] buf = str.getBytes();
DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.191.1"), 10000);
ds.send(dp);
ds.close();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
二、创建UDP传输的接收端
1、建立UDP的Socket服务,因为要接收数据,所以必须明确一个端口号;
2、创建数据包,用于存储接收到的数据,方便用数据包对象的方法解析这些数据;
3、使用UDP的Socket服务的receive方法接收数据并存储到数据包中;
4、通过数据包的方法解析这些数据;
5、关闭Socket服务。
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDPReceive {
public static void main(String[] args) throws IOException {
System.out.println("接收端启动......");
DatagramSocket ds = new DatagramSocket(10000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
ds.receive(dp);
String ip = dp.getAddress().getHostAddress();
int port = dp.getPort();
String text = new String(dp.getData(), 0, dp.getLength());
Syst