繁体   English   中英

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

[英]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.

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