1

This is my structs' definition

    public struct SPMSifHdr
    {
        public UInt32 ui32Synch1;
        public UInt32 ui32Synch2;
        public ushort ui16Version;
        public UInt32 ui32Cmd;
        public UInt32 ui32BodySize;
    };

    struct SPMSifReturnKcdLclMsg
    {
        public SPMSifHdr hdr1;
        public char ff;
        public char[] Dta;
        public bool Debug;
        public char[] szOpId;
        public char[] szOpFirst;
        public char[] szOpLast;
    }

How to convert struct SPMSifReturnKcdLclMsg to array of bytes to send via tcp/ip?
Forgive my language, I can't use english very well :p

6
  • Once the byte-converted struct comes to the other side of the TCP/IP channel, how do you want to convert it back ? Do both sides share the dll containing the struct definition ? Commented Mar 20, 2012 at 9:28
  • i just make the client program. the program should send the formatted data to an interface Commented Mar 20, 2012 at 9:33
  • So the tcp listener needs a way to understand the bytes. If you use the binary serialization the other side needs the assembly containing the struct definitions to be able to deserialize it. Commented Mar 20, 2012 at 9:39
  • 2
    @YkmLo, I would recommend XML Serialization or JSON serialization over binary serialization. You also need to consider version-ing your data-structures and/or serialization logic if there is possibility of server serving different version on clients! Commented Mar 20, 2012 at 9:42
  • @YkmLo: I agree with VinayC. You could also use protobuf serialization that is very small and fast. Commented Mar 20, 2012 at 9:48

1 Answer 1

3
Socket socket = OpenSocket();
using (var stream = new NetworkStream(socket))
{
    var formatter = new BinaryFormatter();
    formatter.Serialize(stream, obj); 
}

EDIT:
Forgot to mention that your structs should be marked as Serializable

Sign up to request clarification or add additional context in comments.

3 Comments

Do the structs need to be marked as Serializable for this to work?
@YkmLo: Just put [Serializable] attribute over the two struct definitions.
I wouldn't recommend using binary formatter for byte conversion - its .NET proprietary serialization. Unless the code at receiving end is also .NET, you are probably rely on serialization format out-side your control. Even if the receiving part is .NET code then also one may need to add some kind of versioning logic...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.