可能重复:
如何在 C# 中异步接收复杂对象?
我的复杂对象的类型是 IOrderedQueryable 它有 4 个属性,都是 List 类型
我通过这个使用异步套接字发送我的对象:
private void SendDatabaseObj(Socket handler, IOrderedQueryable<BuildHistory1> buildHistoryQueryResult)
{
byte[] byteData = ObjectToByteArray(buildHistoryQueryResult);
// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), handler);
}
ObjectToByteArray() 函数(发送前序列化对象):
private byte[] ObjectToByteArray(Object obj)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, obj);
return ms.ToArray();
}
我收到了我通过这个发送的对象:
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. But how to store?
// 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)
{
//Use the deserializing function here to retrieve the object to its normal form
}
// Signal that all bytes have been received.
receiveDoneQuery.Set();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
我的反序列化功能:
private Object ByteArrayToObject(byte[] arrayBytes)
{
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
ms.Write(arrayBytes, 0, arrayBytes.Length);
ms.Seek(0, SeekOrigin.Begin);
Object obj = (Object)bf.Deserialize(ms);
return obj;
}
现在我的问题是接收函数“ReceiveCallback_onQuery()”。如果有更多的数据要接收,如何存储之前接收到的数据?
编辑:我知道执行下面的代码,但是还有其他方法可以将接收到的数据存储在 byte[] 变量中,以便我可以将它们转换回 IOrderedQueryable
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));