我找不到这个问题的解决方案:我在 android 上制作了一个程序来拍摄一张图片(jpg 格式)并通过蓝牙通道将其发送到嵌入式 Windows XP 电脑。我还为 Windows 制作了 C++ 应用程序来接收图片。
通信是使用蓝牙套接字实现的。在 Android 中,应用程序以 1024 字节的块读取文件,并将每个块写入套接字上,直到图片完成。在 Windows 端,我读取 1024 个字节的字节,直到 recv(...) 函数返回一个 > 0 的值。
结果是,在 Android 端,似乎所有字节都被正确读取和发送,但在 Windows 端,我(几乎)总是只收到 70-80% 的字节。我什至可以看到接收到的正确字节,因为可以看到 jpg(图像底部缺失的字节显示为灰色)。我很少能收到完整的图片。这里我贴出Android端的相关部分代码:
String picturePath = "/sdcard/VERDE/PTR-0_15-31-24.jpg";
File picture = new File(picturePath);
if (picture.exists())
{
Log.d(TAG, "File " + picture.getAbsolutePath() + " exists!");
try
{
FileInputStream fis = new FileInputStream(picture);
ostream = socket.getOutputStream();
byte[] buf = new byte[1024];
int read = 0;
int totBytes = 0;
while ((read = fis.read(buf)) != -1)
{
totBytes = totBytes + read;
ostream.write(buf, 0, read);
Log.d(TAG, "Image - Read: " + read + " - Total "
+ totBytes + " bytes!");
}
ostream.flush();
ostream.close();
fis.close();
} catch (UnknownHostException ex)
{
System.out.println(ex.getMessage());
} catch (IOException ex)
{
System.out.println(ex.getMessage());
}
} else
{
Log.d(TAG, "File " + picture.getAbsolutePath()
+ " does not exist!");
}
这是 C++ 应用程序代码的相关部分:
if (_outFile != NULL)
{
_outFile.open(result.c_str(), ofstream::binary); //"pic.jpg"
cout << "File opened!" << endl;
} else
{
cout << "Can't open file!" << endl;
}
while ((received = recv(client, buf, sizeof(buf), 0)) > 0)
{
cout << "R:" << received << " ";
if (received > 0)
{
totalBytes += received;
if (_outFile.is_open())
{
_outFile.write(buf, received);
cout << " (Total: " << totalBytes << " B)" << endl;
} else
cout << "Error in recv() function, received bytes = "
<< received << endl;
} else
cout << "R:" << received << " ";
}
我已经看过数十个关于这个主题的博客和帖子,但似乎没有人有类似的问题!如果您有任何想法,请帮助我!
谢谢!