java实现udp通信客户端代码
时间: 2023-10-02 22:13:33 浏览: 109
以下是一个简单的Java UDP客户端示例代码:
```java
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];
String sentence = "Hello UDP 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("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
```
这段代码创建了一个DatagramSocket对象作为客户端套接字,然后通过InetAddress对象获取本地主机地址。接下来,我们将要发送的字符串转换为字节数组,并将其发送到指定的服务器地址和端口号。最后,客户端等待接收来自服务器的响应,并将其打印在控制台上。
阅读全文