如何在C#中异步接收复杂对象?

时间:2012-11-19 11:22:59

标签: c# sockets asynchronous

编辑: A more concise explanation of what I was trying to do here and with answers

我正在使用c#异步套接字从源接收数据。

我的问题是如果有更多要收到的数据,如何以及在何处存储收到的数据?

收到字符串后,我可以使用字符串构建器从msdn接收和存储:

private void ReceiveCallback_onQuery(IAsyncResult ar)
        {
            try
            {
                // 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)
                {
                    // There might be more data, so store the data received so far.
                    dataReceived += state.buffer; //Does not work (dataReceived is byte[] type)

                    // Get the rest of the data.
                    client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                        new AsyncCallback(ReceiveCallback_onQuery), state);
                }
                else
                {
                    // All the data has arrived; put it in response.
                    if (dataReceived > 1)
                    {
                        response_onQueryHistory = ByteArrayToObject(dataReceived)
                    }
                    // Signal that all bytes have been received.
                    receiveDoneQuery.Set();
                    }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

我不想将收到的数据转换成字符串,就像我的情况一样,我收到一个复杂的对象。

发送的数据是序列化的,我也可以进行反序列化。

我的问题是如何“不断”从套接字接收数据而不使用字符串生成器来存储它。

谢谢!

2 个答案:

答案 0 :(得分:1)

这取决于在按故障字节按下线路之前复杂事物是如何序列化的,您将接收这些字节并使用相同的算法/技术来序列化事物以将其反序列化为其原始状态

对于更具体的答案,我会问你自己更具体。

答案 1 :(得分:1)

My problem is how and where to store received data if there are more to be received?

可以使用Buffer.BlockCopy并将其排队,例如,

           int rbytes = client.EndReceive(ar);

            if (rbytes > state.buffer)
            {
                byte[] bytesReceived = new byte[rbytes];
                Buffer.BlockCopy(state.buffer, 0, bytesReceived, 0, rbytes);
                state.myQueue.Enqueue(bytesReceived);                
                    client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReceiveCallback_onQuery), state)
            }