确保收到所有数据

时间:2014-07-08 13:49:54

标签: c# winsock

我正在关注this example,但我遇到了问题。我的客户端/服务器连接的顺序如下:

  
      
  1. 服务器始终在侦听新客户
  2.   
  3. 客户端启动连接
  4.   
  5. 服务器发送一个包含连接信息(9字节)的小数据包,客户端接收
  6.   
  7. 客户端发送响应连接信息,服务器接收
  8.   
  9. 更多来回包
  10.   

我的代码在第3步中遇到了问题,因为第一次调用BeginReceive实际上是一次接收所有数据,但它进入另一个BeginReceive调用,即使没有更多数据得到。我使用的自定义服务器实现已经以与iOS应用程序相同的方式进行通信。

我是否可以执行简单的检查以查看套接字上是否确实有更多数据要接收?

这是我的接收回调函数的实现,启动接收函数是相同的:

    private static void ReceiveCallback(IAsyncResult ar)
    {
        try
        {
            Console.WriteLine ( "Received data" );
            // Retrieve the state object and the client socket 
            // from the asynchronous state object.
            StateObject state = (StateObject)ar.AsyncState;
            Socket client = state.workSocket;

            // Read data from the remote device.
            int bytesRead = client.EndReceive(ar);

            if (bytesRead > 0)
            {
                //First pass reads all 9 bytes the server sent
                Console.WriteLine ( "Received bytes: {0}", bytesRead );
                // There might be more data, so store the data received so far.
                state.ms.Write(state.buffer, 0, bytesRead);

                // Get the rest of the data.
                //Gets stuck in this call because there is no more data to receive
                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReceiveCallback), state);
            }
            else
            {
                Console.WriteLine ( "Received all data? {0}", state.ms.Length );
                // All the data has arrived; put it in response.
                if ( state.ms.Length > 0 )
                {
                    Console.WriteLine ( "Received whole packet" );
                    MyPacketInfo.MyPacket receivedPacket = MyPacketInfo.MyPacket.packetFromMemoryStream ( state.ms );

                    if ( receivedPacket != null )
                    {
                        state.caller.ReceivedPacket ( receivedPacket, client );
                    }
                    else
                    {
                        Console.WriteLine ( "Received bad packet!" );
                    }
                }

                // Signal that all bytes have been received.
                receiveDone.Set();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

0 个答案:

没有答案