java 编写一个UDP数据报网络程序,分别定义网络通信的两端:ClientA、ClientB。其中,ClinetA中连续向ClientB发送2个数据报,分别为:“你好”、“我是ClinetA”;ClientB分别接收对方发来的2个数据报,并将接收到的内容显示在命令行窗口。
时间: 2024-03-01 10:56:28 浏览: 62
以下是Java的实现代码:
在ClientA中:
```java
import java.net.*;
public class ClientA {
public static void main(String[] args) throws Exception {
// 定义服务器地址和端口号
InetAddress serverAddress = InetAddress.getByName("localhost");
int port = 8888;
// 创建UDP套接字
DatagramSocket clientSocket = new DatagramSocket();
// 发送数据报
String data1 = "你好";
byte[] bytes1 = data1.getBytes();
DatagramPacket packet1 = new DatagramPacket(bytes1, bytes1.length, serverAddress, port);
clientSocket.send(packet1);
String data2 = "我是ClientA";
byte[] bytes2 = data2.getBytes();
DatagramPacket packet2 = new DatagramPacket(bytes2, bytes2.length, serverAddress, port);
clientSocket.send(packet2);
// 关闭套接字
clientSocket.close();
}
}
```
在ClientB中:
```java
import java.net.*;
public class ClientB {
public static void main(String[] args) throws Exception {
// 定义服务器地址和端口号
InetAddress serverAddress = InetAddress.getByName("localhost");
int port = 8888;
// 创建UDP套接字
DatagramSocket serverSocket = new DatagramSocket(port);
// 接收数据报
byte[] buffer = new byte[1024];
// 接收第一个数据报
DatagramPacket packet1 = new DatagramPacket(buffer, buffer.length);
serverSocket.receive(packet1);
String data1 = new String(packet1.getData(), 0, packet1.getLength());
System.out.println(data1);
// 接收第二个数据报
DatagramPacket packet2 = new DatagramPacket(buffer, buffer.length);
serverSocket.receive(packet2);
String data2 = new String(packet2.getData(), 0, packet2.getLength());
System.out.println(data2);
// 关闭套接字
serverSocket.close();
}
}
```
注意:需要先启动ClientB程序,再启动ClientA程序,否则会出现连接失败的情况。
阅读全文