send struct through network

  • Thread starter Thread starter Dirk Reske
  • Start date Start date
D

Dirk Reske

Hey,

I have following struct:

struct Packet
{
string Command;
string[] Args;
byte[] Data;
}

how can I send (and receive) this throug a network? (some example code)

thx
 
Dirk Reske said:
I have following struct:

struct Packet
{
string Command;
string[] Args;
byte[] Data;
}

how can I send (and receive) this throug a network? (some example code)

It depends how exactly you want to send it. Will serialization do? If so,
then just mark it with the serializable attribute.

The transport mechanism will very much depend on how you take the struct
apart and put it back together again.


--
Regards,

Tim Haughton

Chief Technical Officer
Agitek Ltd
www.agitek.co.uk
 
Dirk,

I would serialize the thing and then send that array of bytes over the
network.

First, declare your structure as serializable:

[Serializable]
struct Packet
{
string Command;
string[] Args;
byte[] Data;
}

When you want to send it, serialize it to a MemoryStream, and get the
array of bytes:

private static byte[] SerializeToByteArray(object graph)
{
// Create a memory stream, and serialize.
using (MemoryStream stream = new MemoryStream())
{
// Create a binary formatter.
IFormatter formatter = new BinaryFormatter();

// Serialize.
formatter.Serialize(stream, graph);

// Now return the array.
return stream.ToArray();
}
}

You can then send that array of bytes over the socket. To reverse the
process, just deserialize the array. I would place a length descriptor
before the content, so you know how much to read.

Hope this helps.
 
Yes,

can somebody write some little piece of code, how to serialize an send it...
I think the receiver side I get myself

Tim Haughton said:
Dirk Reske said:
I have following struct:

struct Packet
{
string Command;
string[] Args;
byte[] Data;
}

how can I send (and receive) this throug a network? (some example code)

It depends how exactly you want to send it. Will serialization do? If so,
then just mark it with the serializable attribute.

The transport mechanism will very much depend on how you take the struct
apart and put it back together again.


--
Regards,

Tim Haughton

Chief Technical Officer
Agitek Ltd
www.agitek.co.uk
 
Back
Top