1

编辑: 对我在这里尝试做的事情和答案的更简洁的解释

我正在使用 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());
            }
        }

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

发送的数据是序列化的,我也可以反序列化。

我的问题是如何“持续”从套接字接收数据而不使用字符串生成器来存储它。

谢谢!

4

2 回答 2

1

这取决于复杂事物在被分解字节中的线下推之前如何序列化,您将接收这些字节并使用用于序列化事物的相同算法/技术将其反序列化回其原始状态。

对于更具体的答案,我会要求您自己更具体。

于 2012-11-19T11:29:49.700 回答
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)
            }
于 2012-11-19T11:47:27.023 回答