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

编辑: 一个更简洁的解释,我在这里尝试做什么和答案

我正在使用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) }