So I have a server and a client that communicate various data back and fourth. Initially I had a complicated method that went through the byte array and converted all of its variables and strings, one by one, into what they were supposed to be. I learned I could put all of the variables into an object and convert it to a byte array using
private static byte[] ObjectToByteArray2(Object obj)
{
if (obj == null)
return null;
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, obj);
return ms.ToArray();
}
And convert it back using
private static Object ByteArrayToObject(byte[] arrBytes)
{
MemoryStream memStream = new MemoryStream();
BinaryFormatter binForm = new BinaryFormatter();
memStream.Write(arrBytes, 0, arrBytes.Length);
memStream.Seek(0, SeekOrigin.Begin);
Object obj = (Object)binForm.Deserialize(memStream);
return obj;
}
The problem is, once I send this byte array across the network to another application, I can't just use this method to convert it back, I get the error "Unable to find assembly 'test1s, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'." test1s is just the name of the little server program I made to play with this. Obviously the application needs some extra information to convert this array back into an object, so is there any way I can do this, or am I going about the problem wrong?
What I want to accomplish here is have an object of nothing but several variables and strings, convert it to a byte array, send it to another application, and convert it back into the object. This way I don't have to play with the byte array to extract all of my variables and strings.
Thanks
There are a myriad of pre-rolled serialization libraries that will help here. BinaryFormatter has some (IMO) undesirable features here - in particular it will only work with the exact same (well, pretty much) dll at both ends.
XmlSerializer, DataContractSerializer and JavaScriptSerializer are good text-based implementations, and will work fine with a compatible contract at both ends (same properties etc - not necessarily the same type/version).
If you have moderate bandwidth needs, or need better CPU performance I would recommend protobuf-net (caveat: I wrote it) which is a fast binary serializer that may help.
This will work if both sides of the communication channel have a reference to exactly the same assembly and exactly the same version of that assembly, either referenced from the program somehow or living in the GAC.
If you want a mechanism more tolerant of version mismatches, consider using XMLSerializer
instead (but note that addition/removal/changes in fields/properties may result in incorrect behavior if versions don't match up).
If a compact format is required, you might consider looking at Google Protocol Buffers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With