java.net中实现数据报功能
时间: 2024-05-03 15:17:41 浏览: 12
Java中实现数据报功能需要使用java.net包中的DatagramSocket和DatagramPacket类。
DatagramSocket类是一个基于UDP协议的Socket实现,它可以用来发送和接收数据报。DatagramPacket类则是数据报的封装类,它包含了要发送或接收的数据和目的地址等信息。
以下是一个简单的例子,演示如何使用DatagramSocket和DatagramPacket类来发送和接收数据报:
发送数据报:
```
try {
String message = "Hello, world!";
byte[] buffer = message.getBytes();
InetAddress address = InetAddress.getByName("127.0.0.1");
int port = 12345;
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, port);
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
```
接收数据报:
```
try {
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
DatagramSocket socket = new DatagramSocket(12345);
socket.receive(packet);
String message = new String(packet.getData(), 0, packet.getLength());
System.out.println("Received message: " + message);
} catch (IOException e) {
e.printStackTrace();
}
```
在这个例子中,我们发送了一个包含"Hello, world!"字符串的数据报到127.0.0.1的12345端口。然后我们在同一台机器上监听12345端口,等待接收数据报。当收到数据报后,我们将其转换成字符串并输出。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)