C#ProtoBuf与TcpClient如何分离数据包?

时间:2014-10-23 12:55:45

标签: c# networking protobuf-net packet

我想派两个人上课。

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

此课程来自https://code.google.com/p/protobuf-net/wiki/GettingStarted

而且,现在我编写了这样的客户端。

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

此处,Person p1 Person p2 被序列化为远程服务器。

这是服务器。

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

在这里,如果一次通过字节数组接收所有人(两个),我该如何分开它?

提前致谢...

1 个答案:

答案 0 :(得分:2)

protobuf有线格式未终止 - 这是允许连接=== merge的设计选择,但在许多情况下它是有问题的;坦率地说,它可能更有问题而不是有用。然而! protobuf-net方便地包括自终止辅助方法;基本上,将您的Serialize切换为SerializeWithLengthPrefix,将Deserialize切换为DeserializeWithLengthPrefix