2015-02-10 60 views
0

我已經在服務器和客戶端之間建立了套接字連接。現在我試圖從我的客戶端發送數據到服務器。實際上該數據是一個字節數組,其包含在索引14編號,以27陣列的一個例子是在這裏:如何在套接字流中讀取接收器中的字節(java)

{27, 14, 16, 18, 20, 22, 14, 17, 15, 17} and so on. 

使人們作爲字節數組,因爲數據必須在字節。

難度在於,當我從數組發送一行到服務器時,我不知道如何讀取字符串以外的內容。如果它是一個字符串,它會返回一些奇怪的數字,就像你在圖片中看到的那樣。

enter image description here

一些代碼,我如何做到這一點:

發件人

for (int i = 0; i < data.length; i++) { 
     writer.write(data[i]); 
    } 

    writer.flush(); 
    writer.close(); 

接收機

public void readResponse(Socket client) throws IOException{ 
    String userInput; 
    BufferedReader stdIn = new BufferedReader(new InputStreamReader(client.getInputStream())); 

    System.out.println("Response from client:"); 
    while ((userInput = stdIn.readLine()) != null) { 
     System.out.println(userInput); 

    } 

} 

我的字節數組是由LIK E本:

private byte data[] = new byte[12]; 

如果我改變它以大寫字節,我可以用我的代碼讀出來,但是我不知道,如果它以字節爲單位呢?必須使用一些數學來計算平均值。

private Byte data [] = new Byte [12];

那麼,我該如何閱讀它?

更新:

讓我明白了,我要去使用不同的輸入/輸出流。現在我已經改變了Datainput和輸出流。

代碼如下所示:

服務器

public void readResponse(Socket client) throws IOException{ 

    DataInputStream input = null; 

    byte data; 

    try { 
     input = new DataInputStream(client.getInputStream()); 
    } 
    catch (IOException e) { 
     System.out.println(e); 
    } 

    System.out.println("Response from client:"); 
    while ((data = input.readByte()) != -1) { 
     System.out.println(data); 
    } 

} 

客戶

public void sentData(Socket client) throws IOException{  

    DataOutputStream output = null; 
    try { 
     output = new DataOutputStream(client.getOutputStream()); 
    } 
    catch (IOException e) { 
     System.out.println(e); 
    } 

    for (int i = 0; i < data.length; i++) { 
     output.write(data[i]); 
    } 

    output.flush(); 
    output.close();  
} 

正如你可以在我的客戶看,我想在一個時間來發送一個字節到服務器,但它仍然顯示奇怪的數字,如[?] [?] [?]。

回答

0

所有* Reader類僅用於文本數據。處理二進制數據時,直接使用流。在你的情況下,只需使用BufferedInputStream而不是BufferedInputStreamReader。

+1

更不用說作者... – 2015-02-10 23:07:59

+0

我也使用OutputStreamWriter,也錯了嗎? – Mikkel 2015-02-10 23:09:10

+0

哦,是的。相同的故事。作家僅用於文字。只需使用二進制的原始流。 – kaqqao 2015-02-10 23:15:32

0

還有你的程序必須遵守的TCP協議,它有自己的緩衝和沖洗機制。當您首次使用原始字節流對Java程序進行編碼時,此層的存在並不明顯。

我建議你構建一個確定性的協議,例如,使用像「000」這樣的標記字節來指示傳輸的開始,並使用排除「000」的編碼有效載荷,最後使用「000」來終止傳輸。 (這仍然不能處理好傳輸損耗)。

或者,谷歌的Protocol BufferMsgpack幫助一些中介過程。

相關問題