0

我想byte[]在使用异步套接字发送变量之前对变量的内容进行编码。

private void SendDatabaseObj(Socket handler, BuildHistoryClass buildHistoryQueryResult)
{
    byte[] byteData = ObjectToByteArray(buildHistoryQueryResult);

    // Begin sending the data to the remote device.
    handler.BeginSend(byteData, 0, byteData.Length, 0,
        new AsyncCallback(SendCallback), handler);
}

buildHistoryQueryResult使用此函数进行序列化:

private byte[] ObjectToByteArray(BuildHistoryClass obj)
{
    BinaryFormatter bf = new BinaryFormatter();
    MemoryStream ms = new MemoryStream();
    bf.Serialize(ms, obj);
    return ms.ToArray();
}

什么是“正确”的编码格式,因为我的接收器出现异常:

捕获到 SerializationException 输入流不是有效的二进制格式。起始内容(以字节为单位)为:04-00-00-00-06-0F-00-00-00-04-54-72-75-65-06-10-00 ...

接收方:

        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.
                    state.sb.Append(state.buffer);

                    // 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 (state.sb.Length > 1)
                    {
                        response_onQueryHistory = ByteArrayToObject(state.buffer);
                    }
                    // Signal that all bytes have been received.
                    receiveDoneQuery.Set();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

反序列化功能:

        private BuildHistoryClass ByteArrayToObject(byte[] arrayBytes)
        {
            MemoryStream ms = new MemoryStream();
            BinaryFormatter bf = new BinaryFormatter();
            ms.Write(arrayBytes, 0, arrayBytes.Length);
            ms.Seek(0, SeekOrigin.Begin);
            BuildHistoryClass obj = (BuildHistoryClass)bf.Deserialize(ms);
            return obj;
        }
4

1 回答 1

2

您自己的代码有错误,这可能是导致SerializationException. 在接收方,您有以下代码和注释:

// There might be more data, so store the data received so far.
state.sb.Append(state.buffer);

然而后来(在收到所有数据之后)你有以下内容:

// All the data has arrived; put it in response.
if (state.sb.Length > 1)
{
    response_onQueryHistory = ByteArrayToObject(state.buffer);
}

请注意,您正在反序列化state.buffer应该反序列化的位置state.sb

于 2012-11-20T06:31:24.820 回答