2013-04-24 92 views
0

我想每次从相机捕获图像时,都会自动从我的android手机向服务器(PC)发送多个图像。使用InputStream通过TCP套接字接收多个图像

问题是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 
... 
... 
... 
... 

任何帮助将得到高度赞赏。

+0

任何线索的人? – Saaram 2013-04-24 10:29:55

回答

0

如果你想通过同一个流接收多个图像,你应该建立某种协议,例如:读取一个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在相同的字节顺序比你receving它。

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

+0

不行,亲爱的 – Saaram 2013-04-27 21:11:21