简体   繁体   中英

Listening for incoming messages from TCP server causes StackOverflow

I need to continuously listen for messages from my C# TCP server, so I do it in separate thread:

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();
}

What's wrong with my approach? Why am I getting a StackOverflowError? I'm guessing that run() is invoked incredibly fast because BufferedReader.readLine() is non-blocking, but what can I do about it?

Don't call run() within run() . This is not a recursive function. If you want to keep reading until some condition, wrap this in a while loop. By calling the method you are executing while you are executing it, you are creating another stack frame. What you really want is just to loop.

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);
      }
   }
}

To help illustrate, it kind of works like this...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM