繁体   English   中英

使用InputStream通过TCP套接字接收多个图像

[英]Receiving multiple images over TCP socket using InputStream

每次我从相机捕获图像时,我都试图将多个图像从Android手机自动一个一个地发送到服务器(PC)。

问题是read()函数仅在第一次时阻塞。 因此,从技术上讲,只有一张图像会被接收并完美显示。 但是之后,当is.read()返回-1 ,此函数将不会阻塞并且无法接收多个图像。

该代码对于服务器来说很简单

while (true) {
    InputStream is = null;
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;

    is = sock.getInputStream();

    if (is != null)
        System.out.println("is not null");

    int bufferSize = sock.getReceiveBufferSize();

    byte[] bytes = new byte[bufferSize];
    while ((count = is.read(bytes)) > 0)
    {
        if (filewritecheck == true)
        {
            fos = new FileOutputStream("D:\\fypimages\\image" + imgNum + ".jpeg");
            bos = new BufferedOutputStream(fos);
            imgNum++;
            filewritecheck = false;
        }
        bos.write(bytes, 0, count);
        System.out.println("count: " + count);
    }
    if (count <= 0 && bos != null) {
        filewritecheck = true;
        bos.flush();
        bos.close();
        fos.close();
    }
}

接收图像后的输出为

is not null
is not null
is not null
is not null
is not null
is not null
is not null
is not null
...
...
...
...

任何帮助将不胜感激。

如果要通过同一流接收多个图像,则应建立某种协议,例如:读取一个表示每个图像的字节数的int。

<int><b1><b2><b3>...<bn> <int><b1><b2><b3>...<bn> ...

然后,您可以通过以下方式读取每个图像:

...
is = sock.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);

if (is != null)
    System.out.println("is not null");

while (true) {
    // Read first 4 bytes, int representing the lenght of the following image
    int imageLength = (bis.read() << 24) + (bis.read() << 16) + (bis.read() << 8) + bis.read();

    // Create the file output
    fos = new FileOutputStream("D:\\fypimages\\image" + imgNum + ".jpeg");
    bos = new BufferedOutputStream(fos);
    imgNum++;

    // Read the image itself
    int count = 0;
    while (count < imageLength) {
        bos.write(bis.read());
        count += 1;
    }
    bos.close();
}

请注意,您还必须修改发送方,并将imageLength设置为与接收时相同的字节顺序。

还要注意,一次读取和写入一个字节并不是最有效的方法,但是它更容易,并且缓冲的流可以解决大部分性能影响。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM