java实现udp通信
时间: 2023-07-29 14:06:14 浏览: 111
用java实现UDP通信
4星 · 用户满意度95%
要实现Java的UDP通信,可以通过以下步骤:
1. 创建一个DatagramSocket对象,指定本地端口号。例如:
```
DatagramSocket socket = new DatagramSocket(8888);
```
2. 创建一个DatagramPacket对象,用于发送和接收数据。例如:
```
byte[] sendData = "Hello, world!".getBytes();
InetAddress address = InetAddress.getByName("127.0.0.1");
int port = 9999;
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, address, port);
```
3. 发送数据。使用DatagramSocket的send()方法发送数据。例如:
```
socket.send(sendPacket);
```
4. 接收数据。使用DatagramSocket的receive()方法接收数据。例如:
```
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
socket.receive(receivePacket);
String receiveMessage = new String(receivePacket.getData(), 0, receivePacket.getLength());
```
完整的代码示例:
```
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPExample {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(8888);
byte[] sendData = "Hello, world!".getBytes();
InetAddress address = InetAddress.getByName("127.0.0.1");
int port = 9999;
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, address, port);
socket.send(sendPacket);
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
socket.receive(receivePacket);
String receiveMessage = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Received message: " + receiveMessage);
socket.close();
}
}
```
阅读全文