import java.net.*;public class UDPClient { public static void main(String[] args) throws Exception { DatagramSocket clientSocket = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName("localhost"); byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; while (true) { String sentence = "hello server"; sendData = sentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); clientSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); String modifiedSentence = new String(receivePacket.getData()); System.out.println("Server: " + modifiedSentence); } }}
时间: 2024-03-21 10:44:08 浏览: 65
这是一个Java基于UDP协议的客户端程序,它会向指定IP地址和端口发送消息,并接收来自服务端的响应消息。在这个程序中,客户端会不断发送消息,并等待响应消息,然后将响应消息输出到控制台。
要测试这个程序,你需要先运行一个UDP服务端程序,然后再运行两个客户端程序,分别作为两个用户进行通信。下面是一个简单的UDP服务端程序示例:
```java
import java.net.*;
public class UDPServer {
public static void main(String[] args) throws Exception {
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
System.out.println("Client: " + sentence);
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
```
你可以将上面的服务端程序保存到一个Java文件中,然后用javac命令进行编译。然后再运行两个客户端程序,分别作为两个用户进行通信即可。
阅读全文