我正在使用 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());
}
}
我不想将接收到的数据转换为字符串,因为在我的情况下,我正在接收一个复杂的对象。
发送的数据是序列化的,我也可以反序列化。
我的问题是如何“持续”从套接字接收数据而不使用字符串生成器来存储它。
谢谢!