Receiving multiple images over TCP socket using InputStream

前端 未结 1 1545
暗喜
暗喜 2021-01-26 07:48

I am trying to send multiple images one by one automatically from my android phone to the Server (PC) each time I capture an image from the camera.

The problem is the

1条回答
  •  闹比i
    闹比i (楼主)
    2021-01-26 08:28

    If you want to receive multiple images over the same stream you should establish some kind of protocol, example: read an int that represent the number of bytes of each image.

    ... ... ...
    

    Then you can read each image this way:

    ...
    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();
    }
    

    Note that you also have to modify the sender, and put the imageLength in the same byte order than you are receving it.

    Also note that reading and writting one byte at a time isn't the most efficient way, but it's easier and the buffered streams take care of most of the performance impact.

    0 讨论(0)
提交回复
热议问题