android – UDP数据包(通过WiFi Direct)永远不会到达
作者:互联网
那些阅读我之前的问题的人可能已经知道这一点:我目前正试图抓住整个WiFi Direct的东西.到目前为止我所做的就是创建连接.
我想要做的是通过UDP将数据包发送到groupOwner(其IP当然是已知的) – 但它似乎每次都迷失方向.
这是我的一些代码,我有一个接收文件的服务和一个在后台提交它们的intentservice:
FileReceiverService.java
@Override
public void run() {
Log.d(TAG, "Thread starting...");
try {
app.log("Opening UDP socket to receive files.");
DatagramSocket socket = new DatagramSocket(PORT);
app.log("Socket open!");
socket.setSoTimeout(5000);
app.log("Waiting for packet..");
while (isRunning && !isInterrupted()) {
DatagramPacket packet = new DatagramPacket(
new byte[WiFiPacket.PACKET_SIZE],
WiFiPacket.PACKET_SIZE);
try {
socket.receive(packet);
app.log("Received " + packet.getLength()
+ " bytes, trying to parse!");
parsePacket(packet);
} catch (SocketTimeoutException e) {
} catch (Exception e) {
app.log("Something went wrong: " + e.getMessage());
e.printStackTrace();
}
}
socket.close();
app.log("Closing UDP socket");
} catch (Exception e) {
e.printStackTrace();
}
}
常量WiFiPacket.PACKET_SIZE设置为1024 * 32(32 KB,因为我收到“ERRBLABLA MSG太长”错误,值较高).
FileTransferService.java
@Override
protected void onHandleIntent(Intent intent) {
App app = (App) getApplication();
Context context = getApplicationContext();
boolean rightIntent = false;
WiFiFile file = null;
if (intent.getAction().equals(ACTION_SEND_TEXT)) {
rightIntent = true;
file = WiFiFile.fromText(intent.getExtras().getString(EXTRAS_TEXT));
} else if (intent.getAction().equals(ACTION_SEND_FILE)) {
rightIntent = true;
file = WiFiFile.fromFile(intent.getExtras().getString(
EXTRAS_FILE_PATH));
}
if (rightIntent && file != null) {
app.getOnWiFiTransmissionChangedListener().onNewOutgoingTransfer(
file);
String text = intent.getExtras().getString(EXTRAS_TEXT);
String host = intent.getExtras().getString(
EXTRAS_GROUP_OWNER_ADDRESS);
DatagramSocket socket = null;
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
Log.d(TAG, "Sending packets to " + host + ":" + port);
try {
socket = new DatagramSocket();
int bytesSent = 0;
for (WiFiPacket p : file) {
Log.d(TAG, "Preparing another packet..");
byte[] payload = p.getBytes();
DatagramPacket packet = new DatagramPacket(payload,
payload.length, InetAddress.getByName(host), port);
Log.d(TAG, "Sending packet..");
socket.send(packet);
bytesSent += payload.length;
Log.d(TAG, "Packet send! Contained " + payload.length
+ " bytes! All over we've sent about " + bytesSent
+ " bytes!");
List<WiFiFile> list = new ArrayList<WiFiFile>();
list.add(file);
app.getOnWiFiTransmissionChangedListener()
.onTransferProgressChanged(list);
}
app.getOnWiFiTransmissionChangedListener()
.onFileTransferSuccessful(file);
Log.d(TAG, "Client: Data written");
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, e.getMessage());
} finally {
if (socket != null) {
if (socket.isConnected()) {
socket.close();
}
}
}
}
}
代码可能不是最好的,但至于现在我唯一关心的是接收该死的数据包.
标签:wifi-direct,android,udp 来源: https://codeday.me/bug/20190826/1728446.html