I have established a TCP connection between two computers for sending and receiving data back and forth, in a windows application. The message that I am sending is a set of integers converted to string and split by ",". So, for sending the data I'd use,
if (dataSend.Length > 0)
{
m_writer.WriteLine(dataSend);
m_writer.Flush();
}
where dataSend is my message in the form of string, and m_writer is a StreamWriter.
But, now I want to send it as an array of integers over the same network connection but I can't find anything for it. I see a lot of people using byte array but with that I don't understand how, at the time of reading, the receiver would know how to split the bytes into the respective integer.
I realize that the writeline method allows for Int as its parameter too, but how do I send an array?
With string it was clear because I could separate the data based on "," and so I knew where each element would end. What would the separation criteria be for integer array?
It would be nice if someone would explain this to me, as I am also fairly new to the networks aspect of C#.
Follow up question: StreamReader does not stop reading C#
You're asking a question that will almost always end up being answered by using serialization and/or data framing in some form. Ie. "How do I send some structure over the wire?"
You may want to serialize your int[]
to a string using a serializer such as XmlSerializer or the JSON.NET library. You can then deserialize on the other end.
int[] numbers = new [] { 0, 1, 2, 3};
XmlSerializer serializer = new XmlSerializer(typeof(int[]));
var myString = serializer.Serialize(numbers);
// Send your string over the wire
m_writer.WriteLine(myString);
m_writer.Flush();
// On the other end, deserialize the data
using(var memoryStream = new MemoryStream(data))
{
XmlSerializer serializer = new XmlSerializer(typeof(int[]));
var numbers = (int[])serializer.Deserialize(memoryStream);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With