2012-11-19 16 views
1

编辑: A more concise explanation of what I was trying to do here and with answers如何在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()); 
      } 
     } 

我不想我接收到的数据转换成字符串作为我的情况下,我正在接收一个复杂的对象。

发送的数据是序列化的,我也很好反序列化。

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

谢谢!

+0

我没有看到任何“复杂对象”在这里,任何类型的序列化/反序列化的代码,也没有说明这种数据来自于电线,所以回答你的问题相当困难。 – spender

+0

你可能想要研究序列化,例如http://aviadezra.blogspot.ie/2008/07/code-sample-sending-typed-serialized.html ......就像它一样;你还没有真正问过一个有效的问题 –

+0

什么是复杂的对象?很有可能无论你发送什么,它都是首先被序列化的。您需要在收到它后反序列化它。既然你把它放在缓冲区中......应该很容易将它提供给你选择的解串器? – LightStriker

回答

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

谢谢你MSK!我有这个blockcopy,但我从来没有想过需要队列! – Mikk