2013-08-25 117 views
0

我試圖發送兩個android設備之間的圖片,但有一個傳輸問題,我想不出。有人告訴我修改這個可疑的循環,但它仍然不起作用。 當我在設備上測試我的項目時,連接沒有問題。但是,隨着傳輸任務的開始,發送方客戶端被停止,接收方顯示「傳輸錯誤」消息。 有沒有人知道我可以對我的程序做些什麼?這裏是我發送和接收的兩個主要部分。如何正確接收插座

我會非常感謝任何幫助。謝謝。

發送部分:

s = new Socket("192.168.0.187", 1234); 
Log.d("Tag====================","socket ip="+s); 

File file = new File("/sdcard/DCIM/Pic/img1.jpg"); 
FileInputStream fis = new FileInputStream(file); 
din = new DataInputStream(new BufferedInputStream(fis)); 
dout = new DataOutputStream(s.getOutputStream()); 
dout.writeUTF(String.valueOf(file.length())); 
byte[] buffer = new byte[1024]; 
int len = 0; 
while ((len = din.read(buffer)) != -1) { 
    dout.write(buffer, 0, len); 
    tw4.setText("8 in while dout.write(buffer, 0, len);"); 
    } 
dout.flush(); 

發送部分可以順利工作,沒有埃羅出現了while循環痊癒了

後接收部分:

try { 
File file = new File("/sdcard/DCIM/img1.jpg"); 
DataInputStream din = new DataInputStream(new BufferedInputStream(client.getInputStream())); 
bis = new BufferedInputStream(client.getInputStream()); 
Log.d("Tag====================","din="+s); 
    FileOutputStream fos = new FileOutputStream(file); 
    dout = new DataOutputStream(new BufferedOutputStream(fos)); 
    byte[] buffer = new byte[1024]; 
    int len = 0; 
    while ((len = bis.read(buffer)) != -1) { 
      dout.write(buffer, 0, len); 
      } 


    dout.flush(); 
    dout.close(); 
    } catch (Exception e) { 
    handler.post(new Runnable() { 
    public void run() { 
    tw1.setText("transmission error"); 
    }}); 

容納部分周圍似乎連卡在「DataInputStream din = new DataInputStream(new BufferedInputStream(client.getInputStream()));」並抓住例外。

再次感謝。

+0

請提供catched異常的堆棧跟蹤。 – flx

+0

08-26 22:49:25.950:D/OpenGLRenderer(18754):啓用調試模式0 08-26 22:54:00.510:D/libEGL(19098):loaded /system/lib/egl/libEGL_tegra.so 08/26 22:54:00.530:D/libEGL(19098):loaded /system/lib/egl/libGLESv1_CM_tegra.so 08-26 22:54:00.540:D/libEGL(19098):loaded/system/lib/egl/libGLESv2_tegra.so 08-26 22:54:00.570:D/OpenGLRenderer(19098):啓用調試模式0 這裏是logcat,謝謝 –

+0

嗯,你沒有記錄異常。所以它不是在logcat .. – flx

回答

0

你正在用writeUTF()編寫文件長度,但是你永遠不會讀它。如果您要在發送圖像後關閉套接字,則不需要長度:只需發送然後關閉套接字即可。如果你確實需要這個長度的話,讀取吧,用readUTF(),然後從套接字讀取到這個字節的許多字節。

如果你需要這個長度,用writeInt()或writeLong()發送它比將數字轉換爲一個字符串更有意義,將它轉換爲writeUTF()格式,然後將其轉換爲字符串另一端用readUTF(),然後將其轉換回int或long。當然,這也意味着適當地使用readInt()或readLong()。

編輯

有關百萬次(希望我每次一$),複製Java中的流規範的做法是:

while ((count = in.read(buffer)) > 0) 
{ 
    out.write(buffer, 0, count); 
} 

其中「數」是int和'buffer'是長度大於0的字節數組,最好是8192或更多。請注意,你必須循環;您必須將read()結果存儲在變量中;你必須測試這個變量;你必須在write()調用中使用它。

+0

所以,如果我只想發送一張圖片然後關閉套接字。我需要while循環嗎?或者放棄循環而不是os.write(buffer,0,bis.read(buffer))? –

+0

@DoReMi請參閱編輯。 – EJP