带有TcpClient的C#ProtoBuf如何分离数据包

本文关键字:分离 数据包 何分离 TcpClient C#ProtoBuf 带有 | 更新日期: 2023-09-27 18:27:30

我想发送两个人的类。

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

这里,Personp1Personp2被序列化到远程服务器。

这是服务器。

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

这里,如果一次接收到所有人(两个)通过字节数组,我如何将其分离?

提前感谢。。。

带有TcpClient的C#ProtoBuf如何分离数据包

protobuf wire格式没有终止-这是一个允许串联===合并的设计选择,但在许多情况下是有问题的;坦率地说,它可能更多地是有问题的,而不是有帮助的。然而protobuf-net方便地包括自终止辅助方法;基本上,将您的Serialize切换为SerializeWithLengthPrefix,将Deserialize切换至DeserializeWithLengthPrefix