Question How do I put property values of a class into a byte array?

groadsvb

Well-known member
Joined
Nov 13, 2006
Messages
75
Programming Experience
Beginner
I have a class that contains some properties that need to be sent to a server application that is using tcp/ip. Our tcpClient Class needs the data as a byte array. How can I take each property and put them into a continuous array of bytes to be sent to the server app? Below is an example of the data class. I hope this makes since. Thanks.
VB.NET:
Public Class Mydata
Public Property Status() as Int16
Public Property Key() as UInt32
Public Property Rtype as Int16
Public Property dataLength Int32
Public Property data as string
End Class
 
Does the server app just need the property values or does it need to reconstruct an instance of the class again using those values?

If it's the former then you can use a BinaryWriter, which you can sit right on top of the NetworkStream from the TcpClient and write the data directly. You would do basically the opposite thing at the other end with a BinaryReader.

If it's the latter then you should use binary serialisation. You can serialise at one end and deserialise at the other. With just a few lines of code you can convert the entire instance to binary data and write it directly to a Stream and then do the opposite at the other end.
 
Back
Top