编辑: 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());
}
}
我不想我接收到的数据转换成字符串作为我的情况下,我正在接收一个复杂的对象。
发送的数据是序列化的,我也很好反序列化。
我的问题如何'不断'从套接字接收数据,而不使用字符串生成器来存储它。
谢谢!
我没有看到任何“复杂对象”在这里,任何类型的序列化/反序列化的代码,也没有说明这种数据来自于电线,所以回答你的问题相当困难。 – spender
你可能想要研究序列化,例如http://aviadezra.blogspot.ie/2008/07/code-sample-sending-typed-serialized.html ......就像它一样;你还没有真正问过一个有效的问题 –
什么是复杂的对象?很有可能无论你发送什么,它都是首先被序列化的。您需要在收到它后反序列化它。既然你把它放在缓冲区中......应该很容易将它提供给你选择的解串器? – LightStriker