Archived

This topic is now archived and is closed to further replies.

.NET & Sockets

This topic is 5110 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi all, I am VERY new to .NET and I just wanted to write a little application receiving and processing some network-transferred data from another application. Now my simple problem is how to send a struct via the .NET framework AT ALL! I didn''t really expect this to be THAT different from standard C++ but it is. I have my Socket up and running and connected so that''s all working perfectly well. All I want to do is to send a user-defined struct using that socket now. say:
struct MyStruct
{
  int a, b;
};
MyStruct c;
 
Now the easy C++ way would be to use the address and size of that struct to send the data (I know this isn''t safe for reasons of member alignment etc). This apparently doesn''t work for C++ .NET since we do managed code here and pointers and stuff aren''t part of that. Instead the Socket::Send() function expectes a managed array of bytes to send. Now: Is that the way to do it in managed C++ at all? If it is, how do I get that data into a BYTE[]? If not, what would be the way to go? Thanks, Alex

Share this post


Link to post
Share on other sites
If you''re working exclusively with .NET applications, it''s just easier to use the Serialization support in the .NET Framework. That is, for your data structures place a [Serializable] tag at the top. Then use a System.Net.Sockets.NetworkStream object to handle your connection. Then use a System.Runtime.Serialization.Formatters.Binary.BinaryFormatter to move the bits back and forth on the wire.

Share this post


Link to post
Share on other sites
In that case, you might try associating a NetworkStream object with the Socket, then attaching a System.IO.BinaryWriter to the NetworkStream. BinaryWriter will let you send primitive types across the wire.

Alternately you can skip the NetworkStream, create a System.IO.MemoryStream object, associate the BinaryWriter with that class, and then use MemoryStream.ToArray() to get the Byte[] you need for Socket.Send().

Or you could just bite the bullet and used unmanaged code. (To be honest, I usually just skip to this step, so there may be a faster/easier method of doing this in managed code.)

Share this post


Link to post
Share on other sites
Furthermore you should use the StructLayout attribute to specify the layout of the structdata. Use LayoutKind.Sequential (and the Pack-Property) or LayoutKind.Explicit to guarantee that the struct is binary compatible with the unmanged end.

Regards,
VizOne

Share this post


Link to post
Share on other sites