BarryBones41
BarryBones41

Reputation: 1491

How to properly read a TCP stream without blocking

I have a TCP server (async) and TCP client (sync).

The TCP server is sending data to the client like so:

private async Task Send(TcpClient client, CancellationToken ct, string message) {
            Console.WriteLine("Sending Message " + message);
            message += "<EOF>";
            NetworkStream stream = client.GetStream();
            byte[] msg = Encoding.ASCII.GetBytes(message);
            await stream.WriteAsync(msg, 0, msg.Length, ct).ConfigureAwait(false);
        }

My client is calling this read every update

private string ReadStream(){
   if(stream.DataAvailable) 
        return reader.ReadLine();
}

This results in my client blocking. In my code I do have some string building techniques to accumulate the read stream, so that I can search for "<EOF>" to know when this message is done. But it seems that if I do not disconnect the client from the server, the client will hang forever.

What is a better way to continually read a TCP socket from the client's perspective?

Upvotes: 0

Views: 1270

Answers (1)

BugFinder
BugFinder

Reputation: 17868

One of the best solutions to a potentially blocking bit of code is to use a thread so that it doesnt block the UI from anything, or any other code. It runs in its own little world.

Task mytask = Task.Factory.StartNew(myfunc,aparam);

you can even do (along the lines of, not put in coding window to check syntax)

var mytask = Task.Factory.StartNew(myfunc).ContinueWith( result => its_done_func());

So you can tell when its done, you can also use a function to update with all the results. You can of course use lambda's too.

Upvotes: 1

Related Questions