2016-05-30 214 views
1

我想在客戶端 - 服務器體系結構中使用Socket發送一個簡單的字節數組。有問題也與Netbeans的調試,因爲它提供了:通過套接字傳輸字節數組

SocketException:連接重置

所以我下面張貼我的代碼,我真的很喜歡,如果有人可以幫助我。

客戶:

public class TestClient { 

/** 
* @param args the command line arguments 
*/ 
public static void main(String[] args) { 
    try { 
     Socket s = new Socket("127.0.0.1", 3242);  

     byte[] b; 
     b = "Hello".getBytes(); 
     DataOutputStream os = new DataOutputStream(s.getOutputStream()); 
     os.write(b); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 


} 

}

服務器:

public class TestServer { 

public static void main(String[] args) { 
    try { 

     byte[] b = new byte[5]; 
     Socket s = new ServerSocket(3242).accept(); 
     DataInputStream is = new DataInputStream(s.getInputStream()); 
     is.read(b); 
     System.out.println(String.valueOf(b)); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    }   
} 

}

我試圖用InputStream和OutputStream簡單,但行爲是一樣的。

運行上面這些代碼的結果是:

[[email protected] 

謝謝您的關注。

回答

0

嘗試更換此

System.out.println(String.valueOf(b)); 

有了這個:

System.out.println(new String(b)); 

這將使用default encoding您的字節數組轉換爲String。它會工作,如果服務器和客戶端使用相同的default encoding否則你將需要指定爲未來兩側的編碼:

TestClient"Hello".getBytes(encoding)

TestServerSystem.out.println(new String(b, encoding))

+0

問題解決。謝謝。 :) –

+0

npbr,不客氣 –

0

那是因爲在你的情況下,String.valueOf將Object作爲輸入(並將其視爲對象)。

如果您確定收回字符串,則可以撥打new String(b)new String(b, "UTF-8")

+0

現在的結果是[72 ,101,108,108,111]。它是字節中「Hello」的正確表示。從這個角度來看,我該如何獲得「Hello」作爲String?謝謝。 (@NicolasFilotto給了我使用String構造函數的方式)再次感謝。 –