2011-08-12 27 views
0

我從一個套接字發送文件到另一個套接字。在此之後,我嘗試發送一條簡單消息,但這不起作用。有人可以說明原因嗎?Java Socket信息在文件傳輸後不可讀

發送的文件和消息:

byte[] buffer = new byte[16384]; 
InputStream inputStream = new FileInputStream(f); 
OutputStream outputStream = client.getOutputStream(); 
int len = 0; 
while ((len = inputStream.read(buffer)) > 0) { 
    outputStream.write(buffer, 0, len); 
} 
client.shutdownOutput(); 

//Following doesnt work: 
PrintWriter m_out = new PrintWriter(outputStream); 
m_out.println("anfrage erhalten"); 
m_out.flush(); 

接收文件和消息:

File pdfFile = new File("marke.pdf"); 
OutputStream fs = new FileOutputStream(pdfFile); 

OutputStream os = client.getOutputStream(); 
InputStream is = client.getInputStream(); 

byte[] buffer = new byte[16384]; 
int len = 0; 
while ((len = is.read(buffer)) != -1) { 
    fs.write(buffer, 0, len); 
} 
fs.flush(); 
fs.close(); 
client.shutdownOutput(); 

// Here i will receive the Message after the file transfer, but this doesnt work! 
System.out.println(br.readLine()); 
+0

什麼都不起作用,例外?我猜你關閉了'clinet.shutdownOutput()'中的客戶端套接字,但它只是一個猜測... – home

+0

here:System.out.println(br.readLine()); 我應該收到消息「Anfrage erhalten」。但只有NULL和沒有數據。沒有關機是一樣的,這只是一個從任何地方解決我的問題tipp,但它不起作用。如果我發送信息befor我傳輸文件,它的工作原理。 – Fabix123

回答

2

你寫了一個消息已經玩具關閉輸出後的輸出流。通過這樣做你應該得到一個IOException。

此外,您在寫入一些二進制數據後使用相同的流寫入文本數據。如果你這樣做,你必須在另一端找到一種方法來知道二進制數據的結束位置以及文本數據何時開始。如果你像讀取字節一樣讀取字節,那麼你將讀取與文本數據字節連接的二進制數據。

+0

嘿,謝謝你,但我怎麼知道二進制數據結束? – Fabix123

+0

您需要定義一個專用協議。一種方法是編寫二進制數據的長度,然後是二進制數據,然後是文本數據。讀取時,首先讀取長度(n),然後讀取二進制數據(n個字節),然後讀取文本數據。 DataOutputStream和DataInputStream可能會有所幫助。 –

+0

謝謝你,你知道一個網站或什麼地方,我可以找到這些事情的例子或教程? – Fabix123