Java UDP通信示例
Server端
- 初始化DatagramSocket:port和ip
- 用buffer初始化DatagramPacket
- 接收DatagramPacket
- 关闭socket
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class UDPServer {
public static void main(String[] args) {
DatagramSocket socket = null;
try {
try {
socket = new DatagramSocket(8080, InetAddress.getByName("127.0.0.1"));
} catch (UnknownHostException e) {
e.printStackTrace();
}
} catch (SocketException e) {
e.printStackTrace();
}
byte[] buffer = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
try {
socket.receive(receivePacket);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
socket.close();
}
}
String string = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println(string);
}
}
Client
- 初始化DatagramSocket:port和ip
- 用buffer初始化DatagramPacket
- 发送DatagramPacket
- 关闭socket
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class UDPClient {
public static void main(String[] args) {
DatagramSocket socket = null;
try {
socket = new DatagramSocket();
} catch (SocketException e) {
e.printStackTrace();
}
try {
InetAddress ip = InetAddress.getByName("127.0.0.1");
int port = 8080;
byte[] buffer = "Hello world".getBytes();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, ip, port);
try {
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
socket.close();
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}