I would like to encode the contents of my byte[] variable before sending it using asynchronous socket.
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 is serialize using this function:
private byte[] ObjectToByteArray(BuildHistoryClass obj)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, obj);
return ms.ToArray();
}
What would be “proper” encoding format because I am getting an exception in my receiver:
SerializationException was caught
The input stream is not a valid binary format. The starting contents (in bytes) are: 04-00-00-00-06-0F-00-00-00-04-54-72-75-65-06-10-00 …
Receiving side:
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());
}
}
De-serializing function:
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;
}
Your own code has a bug, and it may be the cause of the
SerializationException.On the receiving side you have the following code and comment:
Yet later (after all data has been received) you have the following:
Note that you are de-serialising the
state.bufferwhere you should be de-serialising whatever is instate.sb