侦听来自 TCP 服务器的传入消息会导致 StackOverflow
Listening for incoming messages from TCP server causes StackOverflow
我需要持续监听来自我的 C# TCP 服务器的消息,所以我在单独的线程中进行:
private void StartMessageReceivingLoop()
{
new Thread(){
public void run()
{
String msg = null;
try
{
msg = inputStream.readLine(); // inputStream is a BufferedReader instance.
}
catch (IOException e)
{
e.printStackTrace();
}
if (msg != null && msg != "")
NotifyAndForwardMessage(msg); // Notify listeners about the message.
run(); // Next iteration.
}
}.start();
}
我的方法有什么问题?为什么我会收到 WhosebugError?我猜 run()
被调用得非常快,因为 BufferedReader.readLine()
是非阻塞的,但我能做些什么呢?
请勿在 run()
内调用 run()
。这不是递归函数。如果您想一直阅读直到出现某种情况,请将其包装在一个 while 循环中。通过在执行时调用正在执行的方法,您正在创建另一个堆栈框架。你真正想要的只是循环。
public void run() {
String msg = null;
while(true) { // Or whatever your exit condition is...
try {
msg = inputStream.readLine();
} catch(IOException e) {
// Handle properly.
}
if (msg != null && msg != "") {
NotifyAndForwardMessage(msg);
}
}
}
为了帮助说明,它的工作原理是这样的...
Thread.start()
+ run() // 1 (called by thread)
+ run() // 2 (called by previous run)
+ run() //3 (called by previous run)
+etc... where you'll eventually run out of stack space.
我需要持续监听来自我的 C# TCP 服务器的消息,所以我在单独的线程中进行:
private void StartMessageReceivingLoop()
{
new Thread(){
public void run()
{
String msg = null;
try
{
msg = inputStream.readLine(); // inputStream is a BufferedReader instance.
}
catch (IOException e)
{
e.printStackTrace();
}
if (msg != null && msg != "")
NotifyAndForwardMessage(msg); // Notify listeners about the message.
run(); // Next iteration.
}
}.start();
}
我的方法有什么问题?为什么我会收到 WhosebugError?我猜 run()
被调用得非常快,因为 BufferedReader.readLine()
是非阻塞的,但我能做些什么呢?
请勿在 run()
内调用 run()
。这不是递归函数。如果您想一直阅读直到出现某种情况,请将其包装在一个 while 循环中。通过在执行时调用正在执行的方法,您正在创建另一个堆栈框架。你真正想要的只是循环。
public void run() {
String msg = null;
while(true) { // Or whatever your exit condition is...
try {
msg = inputStream.readLine();
} catch(IOException e) {
// Handle properly.
}
if (msg != null && msg != "") {
NotifyAndForwardMessage(msg);
}
}
}
为了帮助说明,它的工作原理是这样的...
Thread.start()
+ run() // 1 (called by thread)
+ run() // 2 (called by previous run)
+ run() //3 (called by previous run)
+etc... where you'll eventually run out of stack space.