Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send integer array over a TCP connection in c#

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#

like image 850
Sanketh. K. Jain Avatar asked Feb 11 '23 22:02

Sanketh. K. Jain


1 Answers

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);
}
like image 76
Alex Wiese Avatar answered Feb 13 '23 19:02

Alex Wiese