簡體   English   中英

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

我的做法有什么問題? 為什么我得到StackOverflowError? 我猜測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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM