重複の可能性:
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));