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

前端 未结 5 1210
萌比男神i
萌比男神i 2021-01-06 04:01

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

5条回答
  •  清歌不尽
    2021-01-06 04:41

    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);
    }
    

提交回复
热议问题