简体   繁体   中英

I want to read a string array using bufferedreader

I have a Client class that sends a string array by using PrintWriter and the Server class is then supposed to be able to receive these values but I can't find a solution in reading from a string array.

Client class:

    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);
}

Server class: (this is the method where the Server reads whatever the Client sends)

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;
}

You've a problem here:

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

This will send nonsense data, the toString() representation of your String array, over the socket, and if the client is sending nonsense, the server will only read in the same. Instead send your data as individual Strings using a for loop.

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

Or I suppose that you could use an ObjectOutputStream and then just send the entire array, but either way, don't do what you're originally doing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM