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

如何在C#中异步接收复杂对象?,c#,sockets,asynchronous,C#,Sockets,Asynchronous,编辑: 我使用c#异步套接字从源接收数据 我的问题是,如果要接收更多数据,如何以及在何处存储接收到的数据 当收到字符串时,我可以使用字符串生成器从msdn接收并存储如下内容: private void ReceiveCallback_onQuery(IAsyncResult ar) { try { // Retrieve the state object and the client socket

编辑:

我使用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());
            }
        }
我不想将接收到的数据转换成字符串,因为在我的例子中,我接收的是一个复杂的对象

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

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


谢谢

这取决于复杂事物在被推入分解字节之前的序列化方式,您将收到这些字节,并使用用于序列化该事物的相同算法/技术将其反序列化回其原始状态

要得到更具体的答案,我想请你自己更具体一点

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

我在这里没有看到任何“复杂对象”,没有任何类型的序列化/反序列化代码,也没有对即将出现的数据类型的描述,因此很难回答您的问题。。。目前的情况;你还没有真正提出一个有效的问题什么是复杂对象?很有可能,无论你发送什么,它都是第一次像那样被序列化发送的。您需要在收到它后反序列化它。既然你把它放在缓冲区里。。。应该很容易将其提供给您选择的反序列化程序吗?谢谢您的评论。我只想知道如何将从state.buffer接收到的数据存储到变量中。在我的问题中,state.buffer中的数据存储在字符串生成器中?如果我不想使用字符串生成器来存储它该怎么办?感谢您的回复,是的,发送的数据已序列化。但是,我不知道是否已收到所有数据,因此可能需要再次调用接收数据的函数。现在,我将在哪里存储以前收到的数据?谢谢MSK!我有那个区块拷贝,但我从没想过需要排队!