当前位置:   article > 正文

在c++中使用protubuf3,socket的demo_c++ 使用protobuf3

c++ 使用protobuf3

安装
https://www.jianshu.com/p/ea1cdd33f2b3

也可

sudo apt-get install protobuf-c-compiler protobuf-compiler
protoc --version

  • 1
  • 2
  • 3

msg.proto

syntax = "proto3";
package tutorial;
message Person {
   
  string name = 1;
  int32 id = 2;  // Unique ID number for this person.
  string email = 3;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

编译

/usr/local/bin/protoc  -I=./   --cpp_out=./   msg.proto 
  • 1

生成
msg.pb.h,msg.pb.cc

server.cpp
使用 ParseFromString 接口

#include<stdio.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<string.h>
#include<string>
#include<iostream>

#include"msg.pb.h"
using namespace std;
#define SIZE 300

int main(int argc,char *argv[])
{
   
        int server_sock,client_sock,r;
        struct sockaddr_in server_addr,client_addr;
        socklen_t len;
        char buf[SIZE];
        if(argc!=2)
        {
   
                printf("need port\n");
                return 1;
        }
        int port = atoi(argv[1]);
        server_sock = socket(AF_INET,SOCK_STREAM,0);
        memset(&server_addr,0,sizeof server_addr);
        server_addr.sin_family=AF_INET;
        server_addr.sin_addr.s_addr=inet_addr("0.0.0.0");//htonl(INADDR_ANY)
        server_addr.sin_port=htons(port)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/907253
推荐阅读
相关标签
  

闽ICP备14008679号