(简易版本
发送端
import java.io.IOException;
import java.net.*;
public class UDPclient {
public static void main(String[] args) {
try {
DatagramSocket socket = new DatagramSocket();
String msg = "oulaoulaoula";
InetAddress localhost = InetAddress.getByName("localhost");
int port = 9090;
DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.length(), localhost, port);
socket.send(packet);
socket.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
接收端
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UDPserver {
public static void main(String[] args) {
int port = 9090;
try {
DatagramSocket socket = new DatagramSocket(port);
byte[] bytes = new byte[1024];
DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
socket.receive(packet);
System.out.println(packet.getAddress().getHostAddress());
System.out.println(packet.getData().toString());
System.out.println(new String(packet.getData(), 0, packet.getLength()));
socket.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
解释
- 核心代码其实就两行, 建立socket和发包\收包
- 注意收到的字节流直接toString()结果不对, 需要声明String类利用构造函数转换流(具体原因未解)