C# send structure objects through socket

前端 未结 6 1740
自闭症患者
自闭症患者 2020-12-09 22:18

i have done a bit of reading in client/server programming in c#. i am familiar enough with this process to ask the following question:

how do i transmit structure ob

6条回答
  •  一生所求
    2020-12-09 23:06

    You can create a NetworkStream based on a Socket, and use any Stream mechanism to transport your data. That translates your question to: How can I read/write a struct from/to a Stream.

    You can use Serialization but also a BinaryWriter/BinaryReader. For a small struct (like you describe) I would write some custom methods:

    var netStream = new NetworkStream(clientSocket, true);
    var writer = new BinaryWriter(netStream);
    
    writer.Write(data.Value1);
    writer.Write(data.Value2);
    

    For larger structures I would consider Cheeso's Marshaling option.

提交回复
热议问题