- Home /
How to prevent StreamReader from hanging when reading from a socket
I'm trying to implement an IRC client in Unity and I'm hanging when reading from a socket stream. The relevant code looks like this:
sock.Connect(server,port);
if (!sock.Connected)
{
Debug.Log("Failed to connect!");
Application.Quit();
}
socketStream=sock.GetStream();
input = new System.IO.StreamReader(socketStream);
output = new System.IO.StreamWriter(socketStream);
And in update I have Debug.Log(input.ReadLine());
When the the stream runs out the application hangs. Google showed other people had this problem but I didn't find a solution. There are IRC packages available on the asset store so it should be possible.
Answer by FortisVenaliter · Sep 08, 2015 at 07:55 PM
That's just how sockets work. If you request to read data, but there is none there, it thinks you're waiting on some and will hang until it gets it.
What you need to do is either poll the stream to check for data before reading, or run your networking code on a synchronous thread.
I found the answer about an hour after posting that. The input.ReadLine() needs to be in a separate thread so it won't lock up the main thread.
Here is the code I used. How would you poll the stream? I didn't see a method that would let me do that.
using System.Threading;
.
.
.
//in connect method after connecting
readThread = new Thread(new ThreadStart(ReadData));
readThread.Start();
.
.
.
void ReadData()
{
while (true)
Handle$$anonymous$$essage(input.ReadLine());
}