用Java编写一个UDP数据报网络程序,分别定义网络通信的两端:ClientA,Client B。其中,ClinetA中连续向ClientB发送2个数据报,分别为:“你好” “我是ClinetA”;ClientB分别接收对方发来的2个数据报,并将接收到的内容显示在命令行窗口。 要求:本程序只定义2个类ClientA、ClientB,分别代表网络通信的两端; ClientA只发送数据,不接收数据;ClientB只接收数据
时间: 2024-02-26 12:58:22 浏览: 25
好的,这是一个经典的网络编程题目。以下是Java代码实现。
1. ClientA类:
```java
import java.net.*;
public class ClientA {
public static void main(String[] args) throws Exception {
// 创建UDP客户端套接字
DatagramSocket socket = new DatagramSocket();
// 定义要发送的数据
String[] messages = {"你好", "我是ClientA"};
// 定义服务器地址和端口号
InetAddress address = InetAddress.getByName("localhost");
int port = 9000;
// 循环发送数据
for (String message : messages) {
// 将数据转换为字节数组
byte[] data = message.getBytes();
// 创建要发送的数据报
DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
// 发送数据报
socket.send(packet);
}
// 关闭套接字
socket.close();
}
}
```
2. ClientB类:
```java
import java.net.*;
public class ClientB {
public static void main(String[] args) throws Exception {
// 创建UDP服务器套接字
DatagramSocket socket = new DatagramSocket(9000);
// 定义要接收的数据报个数
int num = 2;
// 循环接收数据
for (int i = 0; i < num; i++) {
// 创建要接收的数据报
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
// 接收数据报
socket.receive(packet);
// 解析数据报内容
String message = new String(packet.getData(), 0, packet.getLength());
// 显示接收到的数据
System.out.println("接收到数据:" + message);
}
// 关闭套接字
socket.close();
}
}
```
运行上述代码后,可以在命令行窗口中看到ClientB接收到的两个数据报的内容。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)