我想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;
}