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?