SocketLite
SocketLite copied to clipboard
TcpSocketClient read timeout
How can I set a timeout on a call to ReadAsync?
I mean, I connect to a TCP server and I need to keep receiving data until it doesn't send anymore and to do so I do a ReadAsync
inside a loop until it returns 0 bytes read. The problem is that if I don't set a timeout, the last call to ReadAsync
will hold forever.
I already tried setting the client's ReadStream.ReadTimeout
but it doesn't work.
Any ideas?
Update: this is how I setup my receiving method
async Task<byte[]> ReceiveAsync()
{
if (client.ReadStream.ReadTimeout != 10)
client.ReadStream.ReadTimeout = 10;
List<byte> result = new List<byte>();
int readLength = 0;
do
{
byte[] buffer = new byte[4096];
readLength = await client.ReadStream.ReadAsync(buffer, 0, buffer.Length);
if (readLength > 0)
{
if (readLength < buffer.Length)
Array.Resize(ref buffer, readLength);
result.AddRange(buffer);
}
} while (readLength > 0);
return result.ToArray();
}