简体   繁体   English

我想使用 bufferedreader 读取字符串数组

[英]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 类,它使用 PrintWriter 发送一个字符串数组,然后 Server 类应该能够接收这些值,但是我找不到从字符串数组中读取的解决方案。

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.这将通过套接字发送无意义数据,即您的 String 数组的toString()表示,如果客户端发送无意义数据,服务器将只读取相同的数据。 Instead send your data as individual Strings using a for loop.而是使用 for 循环将您的数据作为单独的字符串发送。

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.或者我想你可以使用 ObjectOutputStream 然后只发送整个数组,但无论哪种方式,都不要做你最初做的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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