UDP面向无连接的数据传输,效率高但是不可靠,容易丢包。
以此发送数据不能超过64K,
//接受UDP消息的端口
public class UDPReceive {
public static void main(String[] args) {
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
DatagramSocket ds = null;
try {
ds = new DatagramSocket(5555);
while (true) {
ds.receive(dp);
System.out.println(new String(buf, 0, dp.getLength()));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (ds != null)
ds.close();
}
}
}
//简单的UDPSender端口
public class UDPSender {
public static void main(String[] args) {
String st = "你好";
DatagramSocket ds = null;
DatagramPacket dp = null;
try {
ds = new DatagramSocket(9999);
dp = new DatagramPacket(st.getBytes(), 0, st.getBytes().length,
new InetSocketAddress("192.168.191.1", 5555));
try {
ds.send(dp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (dp != null)
ds.close();
}
}
}