蓝牙插座上的图片从Android传输到Windows

Picture transfer on Bluetooth sockets from Android to Windows

本文关键字:Android 传输 Windows 插座      更新时间:2023-10-16

我找不到这个问题的解决方案:我在android上制作了一个程序来拍摄一张图片(jpg格式),并通过蓝牙通道将其发送到嵌入式Windows XP pc。我还为Windows制作了C++应用程序来接收图片
通信是使用蓝牙插座实现的。在安卓系统中,该应用程序以1024字节的块读取文件,并将每个块写入套接字,直到图片完成。在Windows端,我读取1024字节的chunck中的字节,直到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 << " ";
}

我看过几十个关于这个话题的博客和帖子,但似乎没有人有类似的问题!如果你有任何想法,请帮帮我!

谢谢!

我遇到了完全相同的问题(但不是普通套接字的bloutoth)。你已经找到什么有用的方法来解决这个问题了吗?我什么都试过了,但还是犯了同样的错误。

否则,我想我发现了问题所在,但我不知道该怎么解决。在最后一个步骤中,当存在<传输了1024个字节,我为一个字符串分配了缓冲区,然后计算字符串的长度,这个长度小于上一步接收到的字节。我认为不知何故,他在最后一步没有收到所有东西,当数据<1024字节

我在代码中发现了问题
我以为它在接收端,实际上它在传输安卓代码
问题是socket.close()函数是在所有字节实际传输之前调用的
我意识到,首先尝试线程。CurrentThread().sleep(2000),但这并没有优化
imho,最好的方法是在客户端和服务器之间实现一个控制数据交换的小协议,以确保图片完全传输(这里是一个伪代码示例):

  1. 客户端使用"clientName:pictureName:picLengthInBytes"进行身份验证
  2. 服务器响应:"AuthenticationOK"
  3. 客户端发送图片字节
  4. 服务器检查:

    if(接收字节==picLengthInBytes)

    回复("pictureOK")

  5. 如果需要,执行其他客户端操作(在我的情况下->删除图片)
然后仅在关闭应用程序或停止线程时关闭套接字。