gpt4 book ai didi

java - BufferedReader.readLine() 暂停我的应用程序?

转载 作者:行者123 更新时间:2023-11-29 05:10:19 27 4
gpt4 key购买 nike

我正在使用这段代码:

while (true) {
sendData("hi");
System.out.println("Data sent!");
BufferedReader inFromServer;
try {
inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException e1) {
inFromServer = null;
e1.printStackTrace();
}
System.out.println("Recieved!"); //I see this de-bug message.
try {
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence); //I do NOT see this de-bug message!
} catch (IOException e) {
e.printStackTrace();
}
}

它成功地将数据发送到服务器 - 并且服务器成功发送回数据:

public void run () {
//handle the session using the socket (example)
try {
sendData("Hi");
System.out.println("Data sent!"); //I see this de-bug message.
} catch (Exception e) {
e.printStackTrace();
}
}

但是由于某些原因,应用程序似乎在 inFromServer.readLine() 方法处暂停。我看到“收到!”调试消息,但不是“FROM SERVER”调试消息。

enter image description here

完全没有错误。它似乎只是卡在那里。

为什么它挂起,我该如何解决?

最佳答案

嗯,这只是意味着 inFromServer 没有收到任何线路。

确保你真的发送了一条线,

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.

看看 readLine 方法:

String readLine(boolean ignoreLF) throws IOException {
StringBuffer s = null;
int startChar;

synchronized (lock) {
ensureOpen();
boolean omitLF = ignoreLF || skipLF;

bufferLoop:
for (;;) {

if (nextChar >= nChars)
fill();
if (nextChar >= nChars) { /* EOF */
if (s != null && s.length() > 0)
return s.toString();
else
return null;
}
boolean eol = false;
char c = 0;
int i;

/* Skip a leftover '\n', if necessary */
if (omitLF && (cb[nextChar] == '\n'))
nextChar++;
skipLF = false;
omitLF = false;

charLoop:
for (i = nextChar; i < nChars; i++) {
c = cb[i];
if ((c == '\n') || (c == '\r')) {
eol = true;
break charLoop;
}
}

startChar = nextChar;
nextChar = i;

if (eol) {
String str;
if (s == null) {
str = new String(cb, startChar, i - startChar);
} else {
s.append(cb, startChar, i - startChar);
str = s.toString();
}
nextChar++;
if (c == '\r') {
skipLF = true;
}
return str;
}

if (s == null)
s = new StringBuffer(defaultExpectedLineLength);
s.append(cb, startChar, i - startChar);
}
}
}

请注意,这一个接收一个 boolean 值,但调用 readLine 只需调用这个并传递 false,除非在 Linux 上。

注意 for(;;) 循环,这是一个无限循环。

尝试连接到从服务器发送的“行”

System.getProperty("line.separator");

关于java - BufferedReader.readLine() 暂停我的应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28814996/

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