[英]I want to read a string array using bufferedreader
我有一個 Client 類,它使用 PrintWriter 發送一個字符串數組,然后 Server 類應該能夠接收這些值,但是我找不到從字符串數組中讀取的解決方案。
客戶端類:
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;
}
你這里有問題:
public Client(String[] data) throws IOException {
connectToServer();
out.println(data);
}
這將通過套接字發送無意義數據,即您的 String 數組的toString()
表示,如果客戶端發送無意義數據,服務器將只讀取相同的數據。 而是使用 for 循環將您的數據作為單獨的字符串發送。
public Client(String[] data) throws IOException {
connectToServer();
for (String line : data) {
out.println(line + "\n");
}
}
或者我想你可以使用 ObjectOutputStream 然后只發送整個數組,但無論哪種方式,都不要做你最初做的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.