Joy Hyuk Lee
Joy Hyuk Lee

Reputation: 776

C# ProtoBuf with TcpClient How can i separate packets?

I want to send two person classes.

[ProtoContract]
class Person {
    [ProtoMember(1)]
    public int Id {get;set;}
    [ProtoMember(2)]
    public string Name { get; set; }
    [ProtoMember(3)]
    public Address Address {get;set;}
}
[ProtoContract]
class Address {
    [ProtoMember(1)]
    public string Line1 {get;set;}
    [ProtoMember(2)]
    public string Line2 {get;set;}
}

This class is from the https://code.google.com/p/protobuf-net/wiki/GettingStarted

And, now i coded client like this.

TcpClient tcp_client = new TcpClient("localhost", 33333);
            var p1 = new Person
            {
                Id = 12345,
                Name = "John1",
                Address = new Address
                {
                    Line1 = "USA",
                    Line2 = "New york",
                }
            };
            var p2 = new Person
            {
                Id = 54321,
                Name = "John2",
                Address = new Address
                {
                    Line1 = "USA",
                    Line2 = "New york",
                }
            };

            NetworkStream ns = tcp_client.GetStream();
            Serializer.Serialize(ns, p1);
            Serializer.Serialize(ns, p2);

            tcp_client.Close();
            Console.Read();

Here, Person p1 and Person p2 are serialized to remote server.

This is the server.

static void Main(string[] args)
        {
            IPAddress ipAddress = System.Net.Dns.GetHostEntry("localhost").AddressList[0];
            TcpListener svr = new TcpListener(ipAddress, 33333);
            svr.Start();

            var client = svr.AcceptTcpClient();
            byte[] b = new byte[1024];
            int read = client.GetStream().Read(b, 0, 1024);
            client.Close();
            svr.Stop();

            // Now parse packet.
            byte[] bb = new byte[read];
            Array.Copy(b, bb, read);

            // If in one time received two persons, how can i separate it?
            Console.Read();
        }

Here, if in one time received all persons (two) by byte array, how can i separate it?

Thanks in advance...

Upvotes: 1

Views: 2313

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062945

The protobuf wire format is not terminated - this was a design choice to allow concatenation === merge, but it is problematic in many cases; frankly it is probably problematic more often than it is helpful. However! protobuf-net conveniently includes self-terminating helper methods; basically, switch your Serialize to SerializeWithLengthPrefix and Deserialize to DeserializeWithLengthPrefix.

Upvotes: 3

Related Questions