gpt4 book ai didi

java - Bufferedreader 停止读取

转载 作者:行者123 更新时间:2023-12-02 09:34:27 26 4
gpt4 key购买 nike

读完整个字符串后,读者会停留在 while 中,甚至不会抛出异常。我正在通过curl 向服务器发送请求。

我尝试更改 curl 的内容类型,更改字符串的内容,并使用另一种方式读取输入,例如扫描仪,但总是卡在 while 上。

curl -H "Content-Type: text/plain" -d "asdasdasdashdiasdasgdasgduascuyasvccccc" 192.168.0.59:8080
    // Read characters from the client via input stream on the socket
in = new BufferedReader(new
InputStreamReader(connect.getInputStream()));
// Get character output stream to client (for headers)
out = new PrintWriter(connect.getOutputStream());
// Get binary output stream to client (for requested data)
dataOut = new BufferedOutputStream(connect.getOutputStream());

// Get first line of the request from the client
input = in.readLine();
// Parse the request with a string tokenizer
if (input == null || input.isEmpty()) {
System.err.println("Invalid input");
return;
}

parse = new StringTokenizer(input);

method = parse.nextToken().toUpperCase();
input = in.readLine();

do {

parse = new StringTokenizer(input);
if (parse.hasMoreTokens()) {
header = parse.nextToken().toUpperCase(); // we get the
HTTP method of the client
}
if (parse.hasMoreTokens()) {
hValue = parse.nextToken().toLowerCase();
}

// Support only GET and HEAD methods, we check
out.println(header + hValue);
System.out.println(header + hValue);
if (header.equals("CONTENT-TYPE:")) {
readFile(in);
}
input = in.readLine();
} while (!input.isEmpty());

private void readFile(BufferedReader file) throws IOException {
try {
int count;
count = 0;

while ((count = file.read()) != -1) {
System.out.print((char) count);
}

} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
file.close();
}
}

日志:

Server started.

Listening for connections on port : 8080 ...

Connection opened. (Mon Aug 26 15:44:49 BRT 2019)

HOST:192.168.0.59:8080

USER-AGENT:curl/7.58.0

ACCEPT:*/*

CONTENT-TYPE:text/plain

Content-Length: 39

asdasdasdashdiasdasgdasgduascuyasvccccc

最佳答案

似乎您的客户端(curl)没有关闭连接,因此

(count = file.read()) != -1

在读取最后一个字符后,计数会反复设置为 0,因此始终返回 true。

您需要确保客户端关闭连接,或者将消息长度与消息一起发送,并在收到发送的字符数后将其关闭在服务器端(在 java 中)。

后者可以像这样完成:

1) 发送

curl -H "Content-Type: text/plain" -d "5asdas" 192.168.0.59:8080

2) 更新代码以首先读取长度,然后倒计时直到 0 并像这样关闭连接

private void readFile(BufferedReader file) throws IOException {
int expectedCount = -1;
try {
int count;
count = 0;

while ((count = file.read()) != -1 && (expectedCount > 0 || expectedCount == -1 ) ) {
if ( expectedCount == -1 ) {
// read count and set in expectedCount
} else {
//do what you need to do with the input
System.out.print((char) count);
}
}

} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
file.close();
}
}

请注意,此解决方案并没有考虑到大量的问题,例如多位长度,但应该足以让您继续下去。

关于java - Bufferedreader 停止读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57663566/

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