protobuf用例编写

1.安装go语言环境,这里省略

2.安装protobuf环境

1>下载https://github.com/golang/protobuf,放到路径$GOPATH/src/github.com/

2>进入protoc-gen-go目录,执行make命令安装protoc-gen-go

3>下载https://github.com/google/protobuf/releases/download/v3.3.0/protoc-3.3.0-linux-x86_64.zip,解压protoc到$GOPATH/bin

环境安装完毕

3.废话不多说,直接写代码,期间有参考此博客:http://blog.csdn.net/eclipser1987/article/details/17355475

进入$GOPATH/src目录,用例工程结构如下:

protst/

-protobuftest/

--RegMessage.proto

--RegMessage.pb.go

-client.go

-server.go

其中ReMessage.pb.go文件是通过在protobuftest路径下执行$ protoc --go_out=. RegMessage.proto命令生成的

完后编写client.go和server.go

4.运行,在protst/路径下,运行go run server.go启动server,新建终端相同目录下运行go run client.go,可以观察到server接受到相关数据并作终端打印


RegMessage.proto代码:

'''

package protobuftest;
  
message RegMessage {  
    required int32 id = 1; // 主键,唯一  
    required string username = 2; // 帐号  
    required string password = 3; // 密码  
    optional string email = 4; // 邮箱(可选)  
}  

'''


生成的RegMessage.pb.go文件稍作修改,内容如下:

'''

// Code generated by protoc-gen-go. DO NOT EDIT.
// source: RegMessage.proto


/*
Package protobuftest is a generated protocol buffer package.


It is generated from these files:
RegMessage.proto


It has these top-level messages:
RegMessage
*/
package protobuftest


import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"


// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf


// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package


type RegMessage struct {
Id               *int32  `protobuf:"varint,1,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 (*RegMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }


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() {
proto.RegisterType((*RegMessage)(nil), "protobuftest.RegMessage")
}


func init() { proto.RegisterFile("RegMessage.proto", fileDescriptor0) }


var fileDescriptor0 = []byte{
// 129 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0x12, 0x08, 0x4a, 0x4d, 0xf7,
0x4d, 0x2d, 0x2e, 0x4e, 0x4c, 0x4f, 0xd5, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x01, 0x53,
0x49, 0xa5, 0x69, 0x25, 0xa9, 0xc5, 0x25, 0x4a, 0x59, 0x5c, 0x5c, 0x08, 0x15, 0x42, 0x7c, 0x5c,
0x4c, 0x99, 0x29, 0x12, 0x8c, 0x0a, 0x4c, 0x1a, 0xac, 0x41, 0x4c, 0x99, 0x29, 0x42, 0x52, 0x5c,
0x1c, 0xa5, 0xc5, 0xa9, 0x45, 0x79, 0x89, 0xb9, 0xa9, 0x12, 0x4c, 0x0a, 0x4c, 0x1a, 0x9c, 0x41,
0x70, 0x3e, 0x48, 0xae, 0x20, 0xb1, 0xb8, 0xb8, 0x3c, 0xbf, 0x28, 0x45, 0x82, 0x19, 0x22, 0x07,
0xe3, 0x0b, 0x89, 0x70, 0xb1, 0xa6, 0xe6, 0x26, 0x66, 0xe6, 0x48, 0xb0, 0x28, 0x30, 0x6a, 0x70,
0x06, 0x41, 0x38, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x77, 0x3a, 0x4e, 0x8a, 0x8c, 0x00, 0x00,
0x00,
}

'''


server.go代码:

'''

package main




import (
        "io"
        "log"
        "net"
)


import proto "github.com/golang/protobuf/proto"
import protst "protst/protobuftest"


func main() {


service := "127.0.0.1:7070"


tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
if err != nil {
log.Fatalf("server: ResolveTCPAddr: %s", err)
}


listener,err := net.ListenTCP("tcp",tcpAddr)


if err != nil {
log.Fatalf("server: listen: %s", err)
}


log.Print("server: listening")
for {
conn, err := listener.Accept()
if err != nil {
log.Printf("server: accept: %s", err)
break
}
log.Printf("server: accepted from %s", conn.RemoteAddr())


go handleClient(conn)


}


}


func handleClient(conn net.Conn) {
defer conn.Close()


buf := make([]byte, 512)
for {
log.Print("server: conn: waiting")
n, err := conn.Read(buf)
if err != nil {
if err != io.EOF {
log.Printf("server: conn: read: %s", err)
}
break
}


msg := new(protst.RegMessage)
if err := proto.Unmarshal(buf, msg); err != nil {
log.Printf("Unmarshal to NewMessage: %v", err)
       }


log.Printf("%d\n", msg.GetId())
log.Printf(msg.GetUsername())
log.Printf(msg.GetPassword())
log.Printf(msg.GetEmail())


log.Printf("server: conn: echo %q\n", string(buf[:n]))
n, err = conn.Write(buf[:n])
log.Printf("server: conn: wrote %d bytes", n)


if err != nil {
log.Printf("server: write: %s", err)
break
}
}
log.Println("server: conn: closed")
}

'''


client.go代码如下:

'''

package main




import "os"
import "net"


import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import protst "protst/protobuftest"


func main() {
    regMessage := &protst.RegMessage{
        Id:       proto.Int32(10001),
        Username: proto.String("vicky"),
        Password: proto.String("123456"),
        Email:    proto.String("[email protected]"),
    }
    buffer, err := proto.Marshal(regMessage)
    if err != nil {
        fmt.Printf("failed: %s\n", err)
        return
    }


    pTCPAddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1: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)
}

'''

你可能感兴趣的:(protobuf用例编写)