Reputation: 571
How can I send variables/objects/data from one program to another in a LAN using TCP Socket? In particular, I want to send variables like TreeNode and ListViewItem. How can I do this? How will a sender program convert the variable to a form which it can send to another program in a LAN? And how will the receiver program bring back the sent variable to it's original form?
EDIT: Found the following code on a website which is no longer available and requested to remove the link.
// Convert an object to a byte array
private byte[] ObjectToByteArray(Object obj)
{
if (obj == null)
return null;
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, obj);
return ms.ToArray();
}
// Convert a byte array to an Object
private 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;
}
Upvotes: 0
Views: 2070
Reputation: 6926
It is called serialization, and there are many types of it. Some types favor certain types of data, some types offer greater speeds than compression ratios, and some types offer greater compression ratios than speeds.
JSON.NET, Google Protocol Buffers, YaxLib...there are plenty, take your pick. Some are easier to use than others. I recommend JSON.NET because there are probably more tutorials online for that one, and it's humanly-readable while you're debugging.
Upvotes: 0
Reputation: 3243
You can serialize the data into a byte array and then send that? The receiver program would then de-serialize the data at the other end.
Upvotes: 3