gpt4 book ai didi

java - 使用哪些缓冲区从 ServerSocket 创建的 Socket 接收输入流?

转载 作者:行者123 更新时间:2023-12-01 12:04:54 25 4
gpt4 key购买 nike

从服务器套接字接收字符串输入并将其输出的一种方法是:

public static void main(String[] args)throws IOException {


Socket clientSocket;
ServerSocket server = new ServerSocket(8878);
try {
while((clientSocket = server.accept()) != null) {
InputStream stream = clientSocket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String nextLine = reader.readLine();
if(nextLine != null) {
System.out.println(nextLine);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}

}

但是,InputStream 可以替换为 BufferedInputStream

这会导致某种“双缓冲区”,即缓冲读取器从已经缓冲的输入流中读取数据吗?

此外,可以使用输入流读取器(没有缓冲读取器)进行读取,并且仍然具有缓冲输入流。

我只是对哪种实现最有效感到困惑(毕竟,任何缓冲区的重点都是提高效率?)。

我的首要任务是不让通过 clientSocket 输入流传入的任何字节丢失。之后,一切都与效率有关。这会影响我应该选择哪种缓冲区组合吗?

请告诉我在上面代码的哪些地方您会使用缓冲区?

最佳答案

Would this result in a sort of a 'double buffer', where a buffered reader reads from an already-buffered input stream?

没有。

Also, one could read with an input stream reader (without buffered reader) and still have a buffered input stream.

毫无意义。

I'm just confused as to which implementation would be most efficient (after all, the whole point of any buffer is increased efficiency?).

毫无意义。您最后两个问题到底在说什么?

My main priority is to not let any of the bytes coming though the clientSocket input stream get lost.

那么你就会失败,因为你只从套接字读取一行。如果您想读取全部内容,假设数据是行:

while ((line = reader.readLine()) != null)

After that it's all about efficiency. Does that effect which combination of buffers I should choose?

同样,如果没有您所讨论内容的示例,这个问题就没有意义。

注意

while((clientSocket = server.accept()) != null)

没有意义。 ServerSocket.accept() 不能返回 null。因此对其进行测试是徒劳的。

关于java - 使用哪些缓冲区从 ServerSocket 创建的 Socket 接收输入流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27682387/

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