mfavant / tubekit

NEW PROJECT https://github.com/crust-hub/avant
MIT License
0 stars 0 forks source link

feat: protobuf #8

Closed gaowanlu closed 1 year ago

gaowanlu commented 1 year ago
syntax = "proto3";

message Person {
  string name = 1;
  int32 age = 2;
}

message MessageHead{
  int32 cmd = 1;
  int32 pack_size = 2;
}
protoc --cpp_out=. person.proto
#include <iostream>
#include <fstream>
#include "person.pb.h" // 包含生成的头文件

int main() {
    // 创建一个 Person 消息对象
    Person person;
    person.set_name("Alice");
    person.set_age(30);

    // 将消息序列化到文件
    std::ofstream output("person.dat", std::ios::binary);
    if (!person.SerializeToOstream(&output)) {
        std::cerr << "Failed to serialize Person." << std::endl;
        return 1;
    }
    output.close();

    // 从文件中反序列化消息
    Person newPerson;
    std::ifstream input("person.dat", std::ios::binary);
    if (!newPerson.ParseFromIstream(&input)) {
        std::cerr << "Failed to parse Person." << std::endl;
        return 1;
    }

    // 输出反序列化后的消息内容
    std::cout << "Name: " << newPerson.name() << std::endl;
    std::cout << "Age: " << newPerson.age() << std::endl;

    return 0;
}

进程通信先发MessageHead,再发协议包 接收同理先接收MessageHead, 再接收协议包