如何在C#for Windows 8 App中正确实现异步StreamSocket接收循环?

时间:2014-04-16 14:45:55

标签: c# sockets windows-8

因此,我尝试创建Win8应用客户端时,我的服务器(在.NET 3.5上运行,并且已经支持.NET 3.5客户端)的StreamSocket连接。我通常能够连接和传输。然而,在问候并登录到服务器之后,一旦大量数据传入客户端,大约一半的时间它会随机停止接收。我已经在下面列出了接收代码:

    private void StartReceive()
    {
        // Ensure we haven't closed and destroyed the socket
        if (Socket == null)
        {
            // I checked, this doesn't get hit
            return;
        }

        // Buffer read data
        SocketReader.InputStreamOptions = InputStreamOptions.Partial;
        IAsyncOperation<uint> taskLoad = SocketReader.LoadAsync(MaxReceiveAmt);

        // Continue immediately if done, otherwise use the handler
        if (taskLoad.Status == AsyncStatus.Completed)
            CompletedLoad(taskLoad, taskLoad.Status);
        else
            taskLoad.Completed = new AsyncOperationCompletedHandler<uint>(CompletedReceive);
    }

    private void CompletedReceive(IAsyncOperation<uint> asyncInfo, AsyncStatus asyncStatus)
    {
        // Ensure we haven't closed and destroyed the socket
        if (Socket == null)
        {
            // I checked, this doesn't get hit
            return;
        }

        //Buffer the data into the byte queue ReceiveCurrBuffer
        if (asyncStatus == AsyncStatus.Completed)
        {
            uint count = asyncInfo.GetResults();
            System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString() + ": Received " + count + " bytes");
            if (count > 0)
            {
                lock (ReceiveCurrBuffer)
                {
                    for (int i = 0; i < count; i++)
                    {
                        ReceiveCurrBuffer.Enqueue(SocketReader.ReadByte());
                    }
                }
            }
        }
        else
        {
            throw new Exception();
        }

        using (EventWaitHandle tmpEvent = new ManualResetEvent(false))
        {
            tmpEvent.WaitOne(TimeSpan.FromSeconds(0.01));
        }

        // Buffer read data
        SocketReader.InputStreamOptions = InputStreamOptions.Partial;
        IAsyncOperation<uint> taskLoad = SocketReader.LoadAsync(MaxReceiveAmt);

        // Continue immediately if done, otherwise use the handler
        if (taskLoad.Status == AsyncStatus.Completed)
            CompletedLoad(taskLoad, taskLoad.Status);
        else
            taskLoad.Completed = new AsyncOperationCompletedHandler<uint>(CompletedReceive);
    }

连接套接字并发送一个小问候数据包后,将调用一次StartReceive。调试输出始终显示它接收16个字节(问候语),然后是60个字节(登录完成),然后是16个字节(创建会话)。然而,在那之后,大约50%的时间它开始记录一堆2048字节行(从服务器加载的数据),另外50%它只是停止接收和超时。它在.NET 3.5客户端中100%的工作时间,所以服务器很好。这必须是竞争条件,对吧?它可能与我初始化LoadAsync任务的方式有关吗?我仍然是新的异步C#功能的初学者,所以我猜我在某个地方做了一个错误的假设...有没有更好的方法来实现永久的监听循环?

0 个答案:

没有答案