gpt4 book ai didi

java - 套接字:BufferedReader/InputStream 和 BufferedWriter/OutputStream 不起作用

转载 作者:行者123 更新时间:2023-11-30 08:13:58 24 4
gpt4 key购买 nike

所以我尝试使用 BufferedReader 和 BufferedWriter 制作服务器/客户端解决方案,但它不起作用!仅使用 DataInputStream 和 DataOutputStream 工作得很好,但 Buffered 对象没有打印任何内容。我的错误在哪里?

public class TServer {

static final int PORT = 8001;
static final int QUEUE = 50;

public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(PORT, QUEUE)) {
Socket socket = serverSocket.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

System.out.println(input.readLine());
output.write("this is the server!");
output.flush();
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}


public class TClient {

static final String HOST = "localhost";
static final int PORT = 8001;

public static void main(String[] args) {
try (Socket socket = new Socket(HOST, PORT)) {
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

output.write("this is the client");
output.flush();
System.out.println(input.readLine());
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}

最佳答案

Using only DataInputStream and DataOutputStream worked perfectly fine, but nothing printed out with the Buffered objects.

客户端正在发送以下内容:

output.write("this is the client");

服务器正在尝试使用 BufferedReader 读取一行:

System.out.println(input.readLine());

但是不会收到任何行,因为没有发送行结束符(因此,该方法将阻塞(服务器也是如此,它不发送行结束符))。请参阅 API BufferedReader ,其中指出:

Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

关于java - 套接字:BufferedReader/InputStream 和 BufferedWriter/OutputStream 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29924341/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com