user6283344
user6283344

Reputation:

Reading byte[] in Client/Server TCP app in a single call

Client app creates a List<Person> data from an ObservableCollection<Person>, then converts the data into a byte[] array and sends the Length of the array to the server before sending the actual array like this:

void SendData(object o)
{
    var data = new List<Person>(ListOfPerson);
    var array = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data));
    socket.Send(BitConverter.GetBytes(array.Length));
    socket.Send(array);
    ListOfPerson.Clear();
}

and server first reads the length from e.Buffer which initially was set to 4, then resets e.Buffer and receives whatever client sends in a single Receive call like this:

void Receive(object sender, SocketAsyncEventArgs e)
{
    int length = BitConverter.ToInt32(e.Buffer, 0);
    SetBuffer(e, length);
    int read = (sender as Socket).Receive(e.Buffer);
    var json = Encoding.UTF8.GetString(e.Buffer);
    SetBuffer(e, 4);
    (sender as Socket).ReceiveAsync(e);
}

void SetBuffer(SocketAsyncEventArgs e, int length) => e.SetBuffer(new byte[length], 0, length);

It doesn't matter how many bytes client sends, server always receives whole thing in one Receive call and read shows that it's received all that! In this particular case I've sent a list of 5 Person that takes a Name and Age

public class Person
{
    public string Name { get; set; }
    public Nullable<int> Age { get; set; }
    public Person(string name, Nullable<int> age)
    {
        Name = name;
        Age = age;
    }
    public override string ToString() => Name + " " + Age;
}

I've copied 9999 words from Lorem ipsum generator and pasted that as Name of all 5 Person and 10 as Age. So the length client sent was 341706 bytes and server received all those in that single call and converted it to json string! Will I always get all data client sends in a single call regardless of the number of bytes in TCP communication?

Upvotes: 0

Views: 142

Answers (0)

Related Questions