Java编程实现基于UDP的ping命令的类似功能,包括服务器端pingServer功能、客户端pingClient功能
时间: 2023-08-09 20:12:17 浏览: 125
基于Java实现 PING 的服务器端和客户端
5星 · 资源好评率100%
以下是基于UDP实现ping命令的Java代码,包括服务器端pingServer功能和客户端pingClient功能。
pingServer代码如下:
```java
import java.net.*;
public class PingServer {
private static final int PORT = 12345;
public static void main(String[] args) throws Exception {
DatagramSocket serverSocket = new DatagramSocket(PORT);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
InetAddress clientAddress = receivePacket.getAddress();
int clientPort = receivePacket.getPort();
String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Received message: " + message);
String response = "Pong";
sendData = response.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress, clientPort);
serverSocket.send(sendPacket);
}
}
}
```
pingClient代码如下:
```java
import java.net.*;
public class PingClient {
private static final int PORT = 12345;
public static void main(String[] args) throws Exception {
DatagramSocket clientSocket = new DatagramSocket();
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
InetAddress serverAddress = InetAddress.getByName("localhost");
for (int i = 0; i < 10; i++) {
String message = "Ping";
sendData = message.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddress, PORT);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String response = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Received response: " + response);
Thread.sleep(1000);
}
clientSocket.close();
}
}
```
运行pingServer和pingClient,可以看到客户端发送了10个Ping消息,服务器端收到后返回Pong消息。
阅读全文