在做手机和服务端通讯时,UDP是其中可用协议之一。不过UDP的缺点在于不能得知发送是否成功,可能会存在掉包的情况但是发送方却并不知道。不过既然UDP能存在,自然有它使用的业务场景。UDP其实很简单,最主要的两个类DatagramSocket和DatagramPacket
UDP接收
发送的部分就更简单了,根据以上拿到的DatagramSocket和DatagramPacket对象做如下事情就可发送。数据将会发送到对方的发送端口
UDP接收
while (true) { // 不停的监听端口
DatagramSocket dataSocket = null;
try {
dataSocket = new DatagramSocket(null);
InetSocketAddress address = new InetSocketAddress(PORT_PASSENGER); // 监听的端口
dataSocket.bind(address);
byte receiveByte[] = new byte[4096];
DatagramPacket dataPacket = new DatagramPacket(receiveByte, receiveByte.length);
String receiveStr; // 定义接收字符串
int i = 0;
while (i == 0) {
dataSocket.receive(dataPacket);
i = dataPacket.getLength();
if (i > 0) { // 有接收内容
receiveStr = new String(receiveByte, 0, dataPacket.getLength());
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
dataSocket.close();
}
}
发送的部分就更简单了,根据以上拿到的DatagramSocket和DatagramPacket对象做如下事情就可发送。数据将会发送到对方的发送端口
String jsonStr = "要发送的字符串";
dataPacket.setData(Base64.encode(jsonStr).getBytes());
dataSocket.send(dataPacket);