2015-10-04 63 views
-3

我有一個客戶端類,它使用PrintWriter發送字符串數組,然後Server類應該能夠接收這些值,但是我無法從中讀取解決方案一個字符串數組。我想使用bufferedreader讀取字符串數組

Client類:

public Client(String[] data) throws IOException { 
    connectToServer(); 
    out.println(data); 
    } 

public void connectToServer() throws IOException { 
String serverAddress = "localhost"; 
Socket socket = new Socket(serverAddress,9898); 
in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
out = new PrintWriter(socket.getOutputStream(),true); 
} 

服務器類: (這是服務器讀取任何客戶端發送的方法)您在這裏的一個問題

public void run(){ 
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
PrintWriter out = new PrintWriter(socket.getOutputStream(),true); 

//this is my problem: i can't read the value from the array using this code 
while(true){ 
String input = in.readLine(); 
if(input == null) break; 
} 
+3

'「......但我無法從字符串數組中讀取解決方案」 - 解決方案就是您想自己編寫代碼的解決方案。讓我們看看你的客戶端代碼和你的服務器嘗試。如果你展示它,並且如果你用代碼討論你的具體問題,那麼我們應該能夠輕鬆地幫助你。 –

+0

嗨鳳凰賴,你的問題太寬泛了。您應該先參加[tour](http://stackoverflow.com/tour)並閱讀[我如何提出一個好問題?](http://stackoverflow.com/help/how-to-ask)。請包括編寫字符串數組的代碼,結果文本和試圖讀取文本的代碼。並試圖找出你的閱讀代碼中的具體問題。 – vanje

+0

另外......值得注意的是,圍繞一個將從內存數據讀取的'Reader'包裝額外級別的緩衝是沒有任何好處的。 –

回答

0

public Client(String[] data) throws IOException { 
    connectToServer(); 
    out.println(data); 
} 

這會發出無意義的數據,toString()表示喲ur字符串數組,通過套接字,並且如果客戶端發送廢話,服務器將只讀取相同的內容。而是使用for循環將數據作爲單獨的字符串發送。

public Client(String[] data) throws IOException { 
    connectToServer(); 
    for (String line : data) { 
     out.println(line + "\n"); 
    } 
} 

或者我想你可以使用一個ObjectOutputStream,然後只將整個陣列,但無論哪種方式,不要做您最初在做什麼。

+0

我沒有想到找到解決方案使用客戶端類。謝謝! – phoenixWright

+0

@phoenixWright:很高興它幫助,並再次感謝您改善您的問題。 –

相關問題