异步套接字编程。无法接收完整数据

时间:2014-08-22 04:37:23

标签: c# .net sockets asynchronous

我按照此链接http://msdn.microsoft.com/en-us/library/bew39x2a(v=vs.110).aspx编写了此程序。

    public string ReceiveResponse(Socket client, int bufferSize)
    {
        // Receive the response from the remote device.
        Receive(client, bufferSize);

        // Wait until we receive entire response. 
        receiveDone.WaitOne();

        return response;
    }

我收到的回电是

       public static void ReceiveCallback(IAsyncResult ar)
    {
        StateObject so = (StateObject)ar.AsyncState;
        Socket s = so.WorkSocket;

        int read = s.EndReceive(ar);

        if (read > 0)
        {
            so.Sb.Append(Encoding.ASCII.GetString(so.Buffer, 0, read));
            s.BeginReceive(so.Buffer, 0, 1024, 0,
                                     new AsyncCallback(ReceiveCallback), so);
        }
        else
        {
            if (so.Sb.Length > 1) // Code never reaching this block??
            {
                //All of the data has been read, so displays it to the console 
                string strContent;
                strContent = so.Sb.ToString();
                Console.WriteLine(String.Format("Read {0} byte from socket" +
                                 "data = {1} ", strContent.Length, strContent));
            }
            receiveDone.Set();
        }
    }

在我的代码中注释了else块永远不会到达所以我的receiveDone手动重置事件永远阻止我的单元测试。

当微软说这是要走的路时,为什么它不适合我?

我真的需要它用于实时和多线程环境。我浪费了很多时间,但无法找到正确的理由为什么会发生这种情况?以及如何解决这个问题?

0 个答案:

没有答案