1) Mark your struct with the [Serializable] Attribute.
2) Using the BinaryFormatter, Serialize the struct to a byte array.
3) Send the byte array via the socket.
4) At the other end Receive the byte array
5) Again, using the BinaryFormatter, Deserialize the byte array back to an
instance of your struct type.
Peter
That's what I did...
My code :
public enum ESender
{
SCA,
SGI,
OTHER
}
[Serializable]
[ StructLayout( LayoutKind.Sequential )]
public unsafe struct MessageFormat
{
public ESender sender;
public int data1;
public int data2;
public double value;
}
This is the Struct
Somewhere in the sender , I do this :
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter fmt = new
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
MemoryStream io = new MemoryStream();
fmt.Serialize(io, msg);
byte[] b = io.GetBuffer();
ClientSocket.Send(b);
This seems to work fine
And, in the receiver side, I do this ...
MessageFormat message;
if (msg.Length > 0)
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter fmt = new
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
MemoryStream io = new MemoryStream();
io.Write(msg, 0, msg.Length);
message = (MessageFormat)fmt.Deserialize(io);
}
But the fmt.Deserialize(io) line leads when executing to this : End of
Stream encountered before parsing was completed.
So, where am i wrong ? what's the deal I missed somehow ?
Nicolas
nicolas ETIENNE said:
Hello,
I want to send through Socket a struct
So, i'd like to do, as I did before in C++, something like
send((void*)myStruct);
where myStruct is a struct with basic types
But, I can't do this in c#
So what's the solution ?
How to send my struct ?
And the recepter side, how to match byte[] to a struct ?
Thanks for all
N.E Toulouse