How to send generics over UDP connection C#?

2019-09-20 06:03发布

I'm wondering is there a way to send some kind of generics for example List <float> floatValues = new List<float>() need to be sent to udp client. I don't know how to do that, any help will be appreciated!

2条回答
Root(大扎)
2楼-- · 2019-09-20 06:50

What you want to do is known as serialization/deserialization

In computer science, in the context of data storage and transmission, serialization, is the process of converting a data structure or object state into a format that can be stored (for example, in a file or memory buffer, or transmitted across a network connection link) and "resurrected" later in the same or another computer environment

Instead of building your own serializer, I would recommend to use one of the existing libraries like XmlSerializer, SoapFormatter, BinaryFormatter, DataContractSerializer , DataContractJsonSerializer, JavaScriptSerializer, Json.Net, ServiceStack, Protobuf.Net ........

Here is an example using Json serialization

//Sender
string jsonString = new JavaScriptSerializer().Serialize(floatValues);
byte[] bytesToSend = Encoding.UTF8.GetBytes(jsonString);

//Receiver
string receivedJson = Encoding.UTF8.GetString(bytesToSend);
List<float> floatValues2 = new JavaScriptSerializer()
                                         .Deserialize<List<float>>(receivedJson);
查看更多
Explosion°爆炸
3楼-- · 2019-09-20 06:56

You can serialize floatValues using some serialization facility (like XmlSerializer, BinaryFormatter or DataContractSerializer) and than deserialize it back.

Or you can create your own "application level protocol" and put to the stream type name and serializer type and use this information during deserialization process.

查看更多
登录 后发表回答