当前位置: 代码网 > it编程>编程语言>Asp.net > C#网络协议第三方库Protobuf的使用详解

C#网络协议第三方库Protobuf的使用详解

2025年12月24日 Asp.net 我要评论
为什么要使用二进制数据通常我们写一个简单的网络通讯软件可能使用的最多的是字符串类型,比较简单,例如发送格式为(head)19|msg:heart|100,x,y,z…,在接收端会解析收到

为什么要使用二进制数据

通常我们写一个简单的网络通讯软件可能使用的最多的是字符串类型,比较简单,例如发送格式为(head)19|msg:heart|100,x,y,z…,在接收端会解析收到的socket数据。

这样通常是完全可行的,但是随着数据量变大,网络吞吐量就变大,可能发送的字符串就不合适了,可能会数据量变大。

举例:

假如你要发送你的年收入和你的坐标,例如你的年收入是一亿两千万(123,456,789)(幸福死了)你的坐标是1.234567,如果通过字符串传输,你的收入就是9位,你的坐标可能你发小数因为精度问题还不准确通常使用二进制发送会大大节省。一个int32是4位,float类型也是4位,这样8位就够了。

看下面的例子:

        static void main(string[] args)
        {
            console.writeline("hello, world!");

            int money = 123456789;
            float x = 1.234567f;
            byte[] moneybyte = bitconverter.getbytes(money);
            byte[] xbyte = bitconverter.getbytes(x);
            console.writeline($"moneybyte: {moneybyte.length},{money} :xbyte: {xbyte.length},{x}" );

            int moneyget = bitconverter.toint32(moneybyte);
            float xget = bitconverter.tosingle(xbyte);
            console.writeline($"moneyget: {moneyget} :xget: {xget}");
		}

输出结果

hello, world!
moneybyte: 4,123456789 :xbyte: 4,1.234567
moneyget: 123456789 :xget: 1.234567

我们看到对于数字32位占4个字节,这样如果是大量的数据就会很节省,甚至你可以使用int16,或者bool占用更小的字节。

对于大量密集的网络程序使用二进制数据进行发送很必要的。

初步思考如何方便的使用二进制或者封装

是不是有这样的疑问,如果要同步一个数据包含很多类型数据,如何拼接和解析呢,好像二进制没有字符串那么直观和好使用。

比如我要同步的数据是如下数据(通常我们把这种格式称作协议),需要发送结构和解析正确的匹配才能解析。

协议头|发送的大小|我的名字|18|123456789|1.234567|我的介绍|结束

对于二进制如果我们有这样的结构

public struct mydata
{
	public string name;
	public int age;
	public int money;
	public float x;
	public string readme;
	 
}

我们可以根据结构体内的属性进行二进制发送就可以了,接收方也有这样的数据结构也进行解析就可以了,这里要注意每个属性的顺序不能是错误的。

网上有一些把结构体或者类打包成二进制的方法,这里就不过多说明了。

使用protobuf

protobuf就是专门为实现这个而生的,从名字就可以看出来。

protobuf 的官方 c# 库是 google.protobuf,可以通过 nuget 包管理器来方便的使用。

我们这里就来简单说一下如何使用:

安装

首先vs里创建一个c#控制台程序。

然后可以通过 nuget安装

第一个协议

我们创建一个person.proto文件

syntax = "proto3";

message person {
  string name = 1;
  int32 age = 2;
  string email = 3;
}

我们需要把这个proto转成c#可以解析的c#程序

我们可以来到protobuf库下载执行程序,这个程序可以把proto解析成c#文件。

我们下载好之后:输入指令

f:\downloads\protoc-29.3-win64\bin>protoc --csharp_out=. person.proto

f:\downloads\protoc-29.3-win64\bin>

具体指令可以参考库里的文档

–csharp_out输出cs文件 .是当前路径

执行成功后会有一个person.cs我们可以放入我们的项目,这样就很容易解析协议了。

生成的cs如下:

// <auto-generated>
//     generated by the protocol buffer compiler.  do not edit!
//     source: test.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021, 8981
#region designer generated code

using pb = global::google.protobuf;
using pbc = global::google.protobuf.collections;
using pbr = global::google.protobuf.reflection;
using scg = global::system.collections.generic;
/// <summary>holder for reflection information generated from test.proto</summary>
public static partial class testreflection {

  #region descriptor
  /// <summary>file descriptor for test.proto</summary>
  public static pbr::filedescriptor descriptor {
    get { return descriptor; }
  }
  private static pbr::filedescriptor descriptor;

  static testreflection() {
    byte[] descriptordata = global::system.convert.frombase64string(
        string.concat(
          "cgp0zxn0lnbyb3rvijikblblcnnvbhimcgruyw1lgaegasgjegska2fnzrgc",
          "iaeobrincgvlbwfpbbgdiaeocwigchjvdg8z"));
    descriptor = pbr::filedescriptor.fromgeneratedcode(descriptordata,
        new pbr::filedescriptor[] { },
        new pbr::generatedclrtypeinfo(null, null, new pbr::generatedclrtypeinfo[] {
          new pbr::generatedclrtypeinfo(typeof(global::person), global::person.parser, new[]{ "name", "age", "email" }, null, null, null, null)
        }));
  }
  #endregion

}
#region messages
[global::system.diagnostics.debuggerdisplayattribute("{tostring(),nq}")]
public sealed partial class person : pb::imessage<person>
#if !google_protobuf_refstruct_compatibility_mode
    , pb::ibuffermessage
#endif
{
  private static readonly pb::messageparser<person> _parser = new pb::messageparser<person>(() => new person());
  private pb::unknownfieldset _unknownfields;
  [global::system.diagnostics.debuggernonusercodeattribute]
  [global::system.codedom.compiler.generatedcode("protoc", null)]
  public static pb::messageparser<person> parser { get { return _parser; } }

  [global::system.diagnostics.debuggernonusercodeattribute]
  [global::system.codedom.compiler.generatedcode("protoc", null)]
  public static pbr::messagedescriptor descriptor {
    get { return global::testreflection.descriptor.messagetypes[0]; }
  }

  [global::system.diagnostics.debuggernonusercodeattribute]
  [global::system.codedom.compiler.generatedcode("protoc", null)]
  pbr::messagedescriptor pb::imessage.descriptor {
    get { return descriptor; }
  }

  [global::system.diagnostics.debuggernonusercodeattribute]
  [global::system.codedom.compiler.generatedcode("protoc", null)]
  public person() {
    onconstruction();
  }

  partial void onconstruction();

  [global::system.diagnostics.debuggernonusercodeattribute]
  [global::system.codedom.compiler.generatedcode("protoc", null)]
  public person(person other) : this() {
    name_ = other.name_;
    age_ = other.age_;
    email_ = other.email_;
    _unknownfields = pb::unknownfieldset.clone(other._unknownfields);
  }

  [global::system.diagnostics.debuggernonusercodeattribute]
  [global::system.codedom.compiler.generatedcode("protoc", null)]
  public person clone() {
    return new person(this);
  }

  /// <summary>field number for the "name" field.</summary>
  public const int namefieldnumber = 1;
  private string name_ = "";
  [global::system.diagnostics.debuggernonusercodeattribute]
  [global::system.codedom.compiler.generatedcode("protoc", null)]
  public string name {
    get { return name_; }
    set {
      name_ = pb::protopreconditions.checknotnull(value, "value");
    }
  }

  /// <summary>field number for the "age" field.</summary>
  public const int agefieldnumber = 2;
  private int age_;
  [global::system.diagnostics.debuggernonusercodeattribute]
  [global::system.codedom.compiler.generatedcode("protoc", null)]
  public int age {
    get { return age_; }
    set {
      age_ = value;
    }
  }

  /// <summary>field number for the "email" field.</summary>
  public const int emailfieldnumber = 3;
  private string email_ = "";
  [global::system.diagnostics.debuggernonusercodeattribute]
  [global::system.codedom.compiler.generatedcode("protoc", null)]
  public string email {
    get { return email_; }
    set {
      email_ = pb::protopreconditions.checknotnull(value, "value");
    }
  }

  [global::system.diagnostics.debuggernonusercodeattribute]
  [global::system.codedom.compiler.generatedcode("protoc", null)]
  public override bool equals(object other) {
    return equals(other as person);
  }

  [global::system.diagnostics.debuggernonusercodeattribute]
  [global::system.codedom.compiler.generatedcode("protoc", null)]
  public bool equals(person other) {
    if (referenceequals(other, null)) {
      return false;
    }
    if (referenceequals(other, this)) {
      return true;
    }
    if (name != other.name) return false;
    if (age != other.age) return false;
    if (email != other.email) return false;
    return equals(_unknownfields, other._unknownfields);
  }

  [global::system.diagnostics.debuggernonusercodeattribute]
  [global::system.codedom.compiler.generatedcode("protoc", null)]
  public override int gethashcode() {
    int hash = 1;
    if (name.length != 0) hash ^= name.gethashcode();
    if (age != 0) hash ^= age.gethashcode();
    if (email.length != 0) hash ^= email.gethashcode();
    if (_unknownfields != null) {
      hash ^= _unknownfields.gethashcode();
    }
    return hash;
  }

  [global::system.diagnostics.debuggernonusercodeattribute]
  [global::system.codedom.compiler.generatedcode("protoc", null)]
  public override string tostring() {
    return pb::jsonformatter.todiagnosticstring(this);
  }

  [global::system.diagnostics.debuggernonusercodeattribute]
  [global::system.codedom.compiler.generatedcode("protoc", null)]
  public void writeto(pb::codedoutputstream output) {
  #if !google_protobuf_refstruct_compatibility_mode
    output.writerawmessage(this);
  #else
    if (name.length != 0) {
      output.writerawtag(10);
      output.writestring(name);
    }
    if (age != 0) {
      output.writerawtag(16);
      output.writeint32(age);
    }
    if (email.length != 0) {
      output.writerawtag(26);
      output.writestring(email);
    }
    if (_unknownfields != null) {
      _unknownfields.writeto(output);
    }
  #endif
  }

  #if !google_protobuf_refstruct_compatibility_mode
  [global::system.diagnostics.debuggernonusercodeattribute]
  [global::system.codedom.compiler.generatedcode("protoc", null)]
  void pb::ibuffermessage.internalwriteto(ref pb::writecontext output) {
    if (name.length != 0) {
      output.writerawtag(10);
      output.writestring(name);
    }
    if (age != 0) {
      output.writerawtag(16);
      output.writeint32(age);
    }
    if (email.length != 0) {
      output.writerawtag(26);
      output.writestring(email);
    }
    if (_unknownfields != null) {
      _unknownfields.writeto(ref output);
    }
  }
  #endif

  [global::system.diagnostics.debuggernonusercodeattribute]
  [global::system.codedom.compiler.generatedcode("protoc", null)]
  public int calculatesize() {
    int size = 0;
    if (name.length != 0) {
      size += 1 + pb::codedoutputstream.computestringsize(name);
    }
    if (age != 0) {
      size += 1 + pb::codedoutputstream.computeint32size(age);
    }
    if (email.length != 0) {
      size += 1 + pb::codedoutputstream.computestringsize(email);
    }
    if (_unknownfields != null) {
      size += _unknownfields.calculatesize();
    }
    return size;
  }

  [global::system.diagnostics.debuggernonusercodeattribute]
  [global::system.codedom.compiler.generatedcode("protoc", null)]
  public void mergefrom(person other) {
    if (other == null) {
      return;
    }
    if (other.name.length != 0) {
      name = other.name;
    }
    if (other.age != 0) {
      age = other.age;
    }
    if (other.email.length != 0) {
      email = other.email;
    }
    _unknownfields = pb::unknownfieldset.mergefrom(_unknownfields, other._unknownfields);
  }

  [global::system.diagnostics.debuggernonusercodeattribute]
  [global::system.codedom.compiler.generatedcode("protoc", null)]
  public void mergefrom(pb::codedinputstream input) {
  #if !google_protobuf_refstruct_compatibility_mode
    input.readrawmessage(this);
  #else
    uint tag;
    while ((tag = input.readtag()) != 0) {
    if ((tag & 7) == 4) {
      // abort on any end group tag.
      return;
    }
    switch(tag) {
        default:
          _unknownfields = pb::unknownfieldset.mergefieldfrom(_unknownfields, input);
          break;
        case 10: {
          name = input.readstring();
          break;
        }
        case 16: {
          age = input.readint32();
          break;
        }
        case 26: {
          email = input.readstring();
          break;
        }
      }
    }
  #endif
  }

  #if !google_protobuf_refstruct_compatibility_mode
  [global::system.diagnostics.debuggernonusercodeattribute]
  [global::system.codedom.compiler.generatedcode("protoc", null)]
  void pb::ibuffermessage.internalmergefrom(ref pb::parsecontext input) {
    uint tag;
    while ((tag = input.readtag()) != 0) {
    if ((tag & 7) == 4) {
      // abort on any end group tag.
      return;
    }
    switch(tag) {
        default:
          _unknownfields = pb::unknownfieldset.mergefieldfrom(_unknownfields, ref input);
          break;
        case 10: {
          name = input.readstring();
          break;
        }
        case 16: {
          age = input.readint32();
          break;
        }
        case 26: {
          email = input.readstring();
          break;
        }
      }
    }
  }
  #endif

}

#endregion


#endregion designer generated code

使用

我们开始使用

static void main(string[] args)
{
    console.writeline("hello, world!");


    var person = new person
    {
        age = 18,
        name = "",
        email = ""
    };
    byte[] serializeddata = person.tobytearray();

    console.writeline($"serialsize {serializeddata.length} :serialized data: "  + bitconverter.tostring(serializeddata));

    // 从字节数组反序列化
    var deserializedperson = person.parser.parsefrom(serializeddata);
    console.writeline($"deserialized person: name={deserializedperson.name}, age={deserializedperson.age}, email={deserializedperson.email}");

}
代码中我们给person赋值,并通过tobytearray二进制转化,得到二进制数组后就可以通过网络发送了。
当接收方收到这个二进制数据就可以通过parsefrom进行解析。

执行结果

hello, world!
serialsize 2 :serialized data: 10-12
deserialized person: name=, age=18, email=

我们看到二进制大小是2是因为使用了一种变长编码 (varint) 的优化方案可以看下官方的文档。通常短数据比较多,使用变长编码的方式能够节省一些。

总结

到这里就结束了。以上就是protobuf的简单使用。

这些仅为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com