UDP傳輸的關鍵代碼如下:
public class UdpHelper {
private int port = "12345";
public UdpHelper(int port) {
this.port = port;
}
//發送,确認和接收端是在同一網絡下
public boolean sendByte(byte[] bytes) {
DatagramSocket ds = null;
try {
ds = new DatagramSocket();
if (bytes == null) return false;
DatagramPacket dp = new DatagramPacket(bytes, bytes.length, InetAddress.getByName("255.255.255.255"), port);
ds.send(dp);
ds.close();
return true;
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
//接收,确認和發送端是在同一網絡下
public byte[] getBytes() {
byte[] buf = new byte[1024];
DatagramSocket ds = null;
DatagramPacket dp = null;
try {
ds = new DatagramSocket(port);
dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ds != null) {
ds.close();
}
}
if (dp == null) return null;
final byte[] netBuf = new byte[dp.getLength()];
System.arraycopy(dp.getData(), dp.getOffset(), netBuf, 0, netBuf.length);
return netBuf;
}
}
前段時間要做一個基于UDP傳輸資料的apk,當時隻弄了一天多,還沒弄完就交接給同僚弄其他的去了,是以界面特醜,也沒什麼其他的功能,就不上圖了,有需要就去下載下傳。APK除了實作了資料傳輸的功能,還用到了滑動退出SwipeBack及本地資料庫litepal兩個第三方架。
PS:UDP是不安全協定,資料可能會丢失,特别注意需要在同一網絡下操作,開始不知道被坑了半天(我這連的是同一熱點);進入APP後先點接收,點發送可以測試,UDP支援多方發送和接收。
下載下傳位址: