用Java编写一个UDP数据报网络程序,分别定义网络通信的两端:ClientA、ClientB。其中,ClinetA中连续向ClientB发送2个数据报,分别为:“你好”、“我是ClinetA”;ClientB分别接收对方发来的2个数据报,并将接收到的内容显示在命令行窗口。 要求:本程序只定义2个类ClientA、ClientB,分别代表网络通信的两端;ClientA只发送数据,不接收数据;ClientB只接收数据。
时间: 2024-02-29 07:51:22 浏览: 52
以下是Java代码实现:
ClientA.java
```java
import java.net.*;
public class ClientA {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
InetAddress address = InetAddress.getByName("localhost");
String[] messages = {"你好", "我是ClientA"};
for (String message : messages) {
DatagramPacket packet = new DatagramPacket(message.getBytes(), message.length(), address, 8888);
socket.send(packet);
System.out.println("ClientA发送数据报:" + message);
Thread.sleep(1000);
}
socket.close();
}
}
```
ClientB.java
```java
import java.net.*;
public class ClientB {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(8888);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
for (int i = 0; i < 2; i++) {
socket.receive(packet);
String message = new String(packet.getData(), 0, packet.getLength());
System.out.println("ClientB接收到数据报:" + message);
}
socket.close();
}
}
```
运行时,先启动ClientB,再启动ClientA,结果如下:
```
ClientB接收到数据报:你好
ClientB接收到数据报:我是ClientA
```
阅读全文