go語言使用protobuf與c++做資料通訊。

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

首先,安裝google的protobuf。安裝流程請參見我以前的部落格

http://blog.csdn.net/eclipser1987/article/details/8525383


安裝proto的go語言外掛程式

go get code.google.com/p/goprotobuf/{proto,protoc-gen-go}


編寫一個簡單的案例,go與c++網路通訊:

RegMessage.proto

package cn.vicky.model.seri;message RegMessage {    required int32 id = 1; // 主鍵,唯一    required string username = 2; // 帳號    required string password = 3; // 密碼    optional string email = 4; // 郵箱(可選)}


執行:
protoc --cpp_out=. RegMessage.proto

protoc --go_out=. RegMessage.proto


產生對應的c++源檔案和go源檔案

RegMessage.pb.h

RegMessage.pb.cc

RegMessage.pb.go


go語言做用戶端代碼:

// Code generated by protoc-gen-go.// source: RegMessage.proto// DO NOT EDIT!package mainimport "fmt"import "os"import "net"import proto "code.google.com/p/goprotobuf/proto"import json "encoding/json"import math "math"// Reference proto, json, and math imports to suppress error if they are not otherwise used.var _ = proto.Marshalvar _ = &json.SyntaxError{}var _ = math.Inftype RegMessage struct {Id               *int32  `protobuf:"varint,10001,req,name=id" json:"id,omitempty"`Username         *string `protobuf:"bytes,2,req,name=username" json:"username,omitempty"`Password         *string `protobuf:"bytes,3,req,name=password" json:"password,omitempty"`Email            *string `protobuf:"bytes,4,opt,name=email" json:"email,omitempty"`XXX_unrecognized []byte  `json:"-"`}func (m *RegMessage) Reset()         { *m = RegMessage{} }func (m *RegMessage) String() string { return proto.CompactTextString(m) }func (*RegMessage) ProtoMessage()    {}func (m *RegMessage) GetId() int32 {if m != nil && m.Id != nil {return *m.Id}return 0}func (m *RegMessage) GetUsername() string {if m != nil && m.Username != nil {return *m.Username}return ""}func (m *RegMessage) GetPassword() string {if m != nil && m.Password != nil {return *m.Password}return ""}func (m *RegMessage) GetEmail() string {if m != nil && m.Email != nil {return *m.Email}return ""}func init() {}func main() {regMessage := &RegMessage{Id:       proto.Int32(10001),Username: proto.String("vicky"),Password: proto.String("123456"),Email:    proto.String("eclipser@163.com"),}buffer, err := proto.Marshal(regMessage)if err != nil {fmt.Printf("failed: %s\n", err)return}pTCPAddr, err := net.ResolveTCPAddr("tcp", "192.168.1.98:7070")if err != nil {fmt.Fprintf(os.Stderr, "Error: %s", err.Error())return}pTCPConn, err := net.DialTCP("tcp", nil, pTCPAddr)if err != nil {fmt.Fprintf(os.Stderr, "Error: %s", err.Error())return}pTCPConn.Write(buffer)}

正常情況下是不建議修改protoc產生的源檔案的,我們這裡圖省事,直接在產生的RegMessage.pb.go添加網路發送代碼。

使用C++編寫簡單的socket伺服器:


/*  * File:   main.cpp * Author: Vicky.H * Email:  eclipser@163.com */#include <cstdio>#include <cstdlib>#include <iostream>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <pthread.h>#include "RegMessage.pb.h"void* connHandler(void *pConn) {    int* _pConn = static_cast<int*> (pConn);    for (;;) {        void* buf = malloc(1024);        int n = read(*_pConn, buf, 1024);                cn::vicky::model::seri::RegMessage regMessage;        regMessage.ParseFromArray(buf, n);                std::cout << regMessage.id() << std::endl;        std::cout << regMessage.username() << std::endl;        std::cout << regMessage.password() << std::endl;        std::cout << regMessage.email() << std::endl;                close(*_pConn);        free(buf);    }    return pConn;}/* *  */int main(void) {    int sock = socket(AF_INET, SOCK_STREAM, 0);    if (sock == -1) {        perror("建立Socket失敗!");        return EXIT_FAILURE;    }    struct sockaddr_in addr;    addr.sin_port = htons(7070);    inet_pton(AF_INET, "192.168.1.98", &addr.sin_addr);    int result;    result = bind(sock, (struct sockaddr*) &addr, sizeof (struct sockaddr_in));    if (result != 0) {        perror("綁定地址失敗!");        return EXIT_FAILURE;    }    result = listen(sock, 10);    if (result != 0) {        perror("監聽失敗!");        return EXIT_FAILURE;    }    for (;;) {        int conn = accept(sock, NULL, NULL);        if (conn == -1) {            perror("與用戶端建立串連失敗!");            continue;        }        pthread_t thread;        pthread_create(&thread, NULL, connHandler, (void*) &conn);    }    return 0;}


需要串連 -lpthread -lprotobuf 


分別運行c++程式,go run RegMessage.pb.go

列印:

1
vicky
123456
eclipser@163.com

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.