在UWP StreamSocket中,我可以在超时的情况下读取数据并在超时后将连接保持打开状态吗? [英] In UWP StreamSocket, can I read data with timeout and leave the connection open if timeout elapses

查看:163
本文介绍了在UWP StreamSocket中,我可以在超时的情况下读取数据并在超时后将连接保持打开状态吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如我在

As I couldn't find any way to peek for data (read data without consuming the buffer) as asked at How to peek StreamSocket for data in UWP apps I'm now trying to make my own "peek" but still no luck.

我看不到如何从StreamSocket读取数据,这种方式将允许我使用超时,并在超时发生时保持连接可用.

I don't see how I can read data from StreamSocket in the manner which will let me use timeouts and leave the connection usable in case if timeout elapses.

最后,问题如下.在我的IMAP客户端中,我从服务器收到响应,如果此响应是否定的,我需要稍等一下,看看服务器是否立即发送了另一个响应(有时,服务器可以执行此操作,并提供其他详细信息)错误或什至零封包关闭连接).如果服务器未发送其他响应,则可以,只需离开方法并返回给调用方即可.然后,调用方可以将更多数据发送到流中,接收更多响应,等等.

In the end, the problem is as follows. In my, let's say, IMAP client, I get response from a server and if this response is negative, I need to wait a bit to see if the server immediately sends yet another response (sometimes, the server can do it, with extra details on the error or even a zero packet 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 a request and getting initial response I need in some cases to read socket once again with a very small timeout interval and if no data arrives, just do nothing.

推荐答案

您可以使用 DataReader 消耗来自StreamSocket的输入流.当至少一个字节的数据时,将返回其LoadAsync()方法.在这里,我们添加了一个取消源,该源将在1秒钟后取消异步任务,以在没有消耗数据的情况下停止DataReader.LoadAsync().

You can use a CancelationTokenSource to generate a timeout and stop an async operation. The DataReader consumes the data from the input stream of the StreamSocket. Its LoadAsync() method will return when there is at least one byte of data. Here, we are adding a cancellation source that will cancel the asynchronous task after 1 second to stop the DataReader.LoadAsync() if no data has been consumed.

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
    }
}

别忘了处理DataReader会关闭流和连接.

Do no forget that disposing the DataReader will close the stream and the connection.

这篇关于在UWP StreamSocket中,我可以在超时的情况下读取数据并在超时后将连接保持打开状态吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆