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

前端 未结 5 1205
萌比男神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:29

    I'm going to give you an answer that assumes you want to actually transmit bytes, to keep the protocol light: if not accept alexw answer instead, because it's a pretty good one.

    You should look at some form of message framing, or at the very least length prefixing. I've been dealing with TCP socket protocols for over a decade, and always used some form of this (mostly message framing). Lately, however, I've been using WCF instead, and that uses (.NET) serialization, so I'd actually tend toward alexw answer, given unlimited bandwidth (and a .NET stack a common architecture, or at least an agreed upon serialization algorithm, on both sides).

    EDIT

    Here's how that might look using simple length prefixing:

    var myArray = new byte[10];
    using (var stream = new MemoryStream())
    using (var writer = new BinaryWriter(stream))
    {
        writer.Write(myArray.Length);
        foreach (var b in myArray)
            writer.Write(b);
    }
    

    Of course, using this technique, both parties have to be in on it: you're establishing an Application-Level Protocol on top of TCP, and both sides have to be talking the same language (e.g., knowing that length is stored in a byte, knowing that we're only sending simple arrays of bytes, without further context ... see message framing for what "further context" might look like).

提交回复
热议问题