2014-09-04 144 views
0

我有一個gui,我點擊一個電腦上的發送按鈕和另一臺電腦上的接收按鈕,它發送文件。問題是我只能發送一次文件,然後我必須重新啓動應用程序。java - 只能發送文件一次

它給失敗的原因是這些: 發送電腦上的「套接字已關閉」,雖然我不明白爲什麼會這麼說。接收PC上的「ArrayIndexOutOfBounds」爲 。

我已經得到了這兩種方法,我用來發送數據:

public void StreamIn() throws Exception {  //FOR RECEIVING FILES 

    byte[] mybytearray = new byte[size]; 
    InputStream is = sock.getInputStream(); 
    fos = new FileOutputStream(FILE_TO_RECEIVE); 
    bos = new BufferedOutputStream(fos); 
    bytesRead = is.read(mybytearray, 0, mybytearray.length); 
    current = bytesRead; 

    do { 
     bytesRead = is.read(mybytearray, current, (mybytearray.length - current)); 
     if (bytesRead >= 0) current += bytesRead; 
    } while (bytesRead > -1); 

    bos.write(mybytearray, 0, current); 
    bos.flush(); 

    if (fos != null) fos.close(); 
    if (bos != null) bos.close(); 
} 

public void StreamOut() throws Exception {  //FOR SENDING FILES 

    fis = new FileInputStream(myFile); 
    bis = new BufferedInputStream(fis); 
    bis.read(mybytearray, 0, mybytearray.length); 
    os = sock.getOutputStream(); 

    os.write(mybytearray, 0, mybytearray.length); 
    os.flush(); 

    if (bis != null) bis.close(); 
    if (os != null) os.close(); 
} 

出於某種原因,OutputStream中不會寫第二次,雖然我關閉並嘗試發送另一個文件之前重新創建。我不明白爲什麼發送電腦會說插座已關閉。

回答

1

您在發送一個文件後關閉套接字。如果您想發送另一個文件,請打開另一個套接字。

NB您的副本外環爲StreamIn()正確的,但在StreamOut().你假設read()填充緩衝區,而你也假設mybytearray是由於文件大不正確的,你因此也假設文件一刀切成int.

的規範方式在Java中複製數據流是:在這兩種方法

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

使用此。

另外flush()之前close()是多餘的。

而且StreamOut()缺少mybytearray.

+0

感謝您的回答聲明,但在這段代碼什麼是「緩衝」?而且,如果沒有最終關閉輸出流,我無法閱讀。這是否也關閉了插座? – Sixtoo 2014-09-06 22:35:28

+0

我看到它也關閉了套接字,解決方案是使用Socket.shutdownOutput() – Sixtoo 2014-09-06 22:48:12

+0

**編輯**不是一個真正的解決方案:你不能重複使用outputstream – Sixtoo 2014-09-06 23:00:35