2013-04-24 98 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