In UWP StreamSocket I can read data with timeout and keep connection open if timeout expires

Since I couldn't find any way to peek into the data (read data without using a buffer) as given in How to Peep a StreamSocket for Data in UWP Apps I am now trying to make my own peek but still no luck.

I don't see how I can read data from the StreamSocket in a way that allows me to use timeouts and keep the connection usable in the event of a timeout.

Ultimately, the problem is this. In my, say, IMAP client, I receive a response from the server, and if that response is no, I need to wait a bit to see if the server sends another response immediately (sometimes the server can do this, with additional details on the error, or even null package to close the connection). if the server didn't send another response, I'm fine, just leaving the method and returning to the caller. The caller can then send more data to the stream, receive more responses, etc.

So, after sending the request and receiving the initial response, I need in some cases to read the socket again with a very small timeout interval and, if no data arrives, just do nothing.

+1


source to share


1 answer


You can use CancelationTokenSource

to create timeout and stop operation async

. DataReader

consumes data from the input stream StreamSocket

. Its method LoadAsync()

will return when there is at least one data byte. Here we add a cancellation source that will cancel the asynchronous task after 1 second to stop DataReader.LoadAsync()

if no data has been used.

var stream      = new StreamSocket();

var inputStream = stream.InputStream;

var reader      = new DataReader(inputStream);
reader.InputStreamOptions   = InputStreamOptions.Partial;

while(true)
{
    try
    {
        var timeoutSource   = new CancellationTokenSource(TimeSpan.FromSeconds(1));
        var data    = await reader.LoadAsync(1).AsTask(timeoutSource.Token);

        while(reader.UnconsumedBufferLength > 0)
        {
            var read    = reader.ReadUInt32();
        }
    }
    catch(TaskCanceledException)
    {
        // timeout
    }
}

      



Don't forget that the utility DataReader

will close the stream and connection.

+2


source







All Articles