├── .gitattributes ├── .gitignore ├── ProtoTest.proto ├── PythonProtobufClient ├── ProtoTest_pb2.py ├── ProtoTest_pb2.pyc └── PyProtoClient.py ├── README.md ├── bin ├── CSVValue.csv └── CSVValues.csv ├── pkg ├── windows_386 │ └── ProtobufTest.a └── windows_amd64 │ └── ProtobufTest.a └── src ├── GoProtoClient ├── CSVV.csv └── GoProtoClient.go ├── GoProtoServer └── GoProtoServer.go ├── ProtoTest.proto └── ProtobufTest └── ProtoTest.pb.go /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | *.sln merge=union 7 | *.csproj merge=union 8 | *.vbproj merge=union 9 | *.fsproj merge=union 10 | *.dbproj merge=union 11 | 12 | # Standard to msysgit 13 | *.doc diff=astextplain 14 | *.DOC diff=astextplain 15 | *.docx diff=astextplain 16 | *.DOCX diff=astextplain 17 | *.dot diff=astextplain 18 | *.DOT diff=astextplain 19 | *.pdf diff=astextplain 20 | *.PDF diff=astextplain 21 | *.rtf diff=astextplain 22 | *.RTF diff=astextplain 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Windows image file caches 2 | Thumbs.db 3 | ehthumbs.db 4 | 5 | # Folder config file 6 | Desktop.ini 7 | 8 | # Recycle Bin used on file shares 9 | $RECYCLE.BIN/ 10 | 11 | # Windows Installer files 12 | *.cab 13 | *.msi 14 | *.msm 15 | *.msp 16 | 17 | # ========================= 18 | # Operating System Files 19 | # ========================= 20 | 21 | # OSX 22 | # ========================= 23 | 24 | .DS_Store 25 | .AppleDouble 26 | .LSOverride 27 | 28 | # Icon must ends with two \r. 29 | Icon 30 | 31 | # Thumbnails 32 | ._* 33 | 34 | # Files that might appear on external disk 35 | .Spotlight-V100 36 | .Trashes 37 | -------------------------------------------------------------------------------- /ProtoTest.proto: -------------------------------------------------------------------------------- 1 | package ProtobufTest; 2 | 3 | message TestMessage { 4 | required string clientName = 1; 5 | required int32 clientId = 2; 6 | optional string description = 3 [default = "NONE"]; 7 | repeated MsgItem messageitems = 4; 8 | 9 | enum ItemType { 10 | TypeX = 0; 11 | TypeY = 1; 12 | TypeZ = 2; 13 | } 14 | 15 | message MsgItem { 16 | required int32 id = 1; 17 | optional string itemName = 2; 18 | optional int32 itemValue = 3; 19 | optional ItemType itemType = 4; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /PythonProtobufClient/ProtoTest_pb2.py: -------------------------------------------------------------------------------- 1 | # Generated by the protocol buffer compiler. DO NOT EDIT! 2 | # source: ProtoTest.proto 3 | 4 | from google.protobuf import descriptor as _descriptor 5 | from google.protobuf import message as _message 6 | from google.protobuf import reflection as _reflection 7 | from google.protobuf import descriptor_pb2 8 | # @@protoc_insertion_point(imports) 9 | 10 | 11 | 12 | 13 | DESCRIPTOR = _descriptor.FileDescriptor( 14 | name='ProtoTest.proto', 15 | package='ProtobufTest', 16 | serialized_pb='\n\x0fProtoTest.proto\x12\x0cProtobufTest\"\xa6\x02\n\x0bTestMessage\x12\x12\n\nclientName\x18\x01 \x02(\t\x12\x10\n\x08\x63lientId\x18\x02 \x02(\x05\x12\x19\n\x0b\x64\x65scription\x18\x03 \x01(\t:\x04NONE\x12\x37\n\x0cmessageitems\x18\x04 \x03(\x0b\x32!.ProtobufTest.TestMessage.MsgItem\x1ap\n\x07MsgItem\x12\n\n\x02id\x18\x01 \x02(\x05\x12\x10\n\x08itemName\x18\x02 \x01(\t\x12\x11\n\titemValue\x18\x03 \x01(\x05\x12\x34\n\x08itemType\x18\x04 \x01(\x0e\x32\".ProtobufTest.TestMessage.ItemType\"+\n\x08ItemType\x12\t\n\x05TypeX\x10\x00\x12\t\n\x05TypeY\x10\x01\x12\t\n\x05TypeZ\x10\x02') 17 | 18 | 19 | 20 | _TESTMESSAGE_ITEMTYPE = _descriptor.EnumDescriptor( 21 | name='ItemType', 22 | full_name='ProtobufTest.TestMessage.ItemType', 23 | filename=None, 24 | file=DESCRIPTOR, 25 | values=[ 26 | _descriptor.EnumValueDescriptor( 27 | name='TypeX', index=0, number=0, 28 | options=None, 29 | type=None), 30 | _descriptor.EnumValueDescriptor( 31 | name='TypeY', index=1, number=1, 32 | options=None, 33 | type=None), 34 | _descriptor.EnumValueDescriptor( 35 | name='TypeZ', index=2, number=2, 36 | options=None, 37 | type=None), 38 | ], 39 | containing_type=None, 40 | options=None, 41 | serialized_start=285, 42 | serialized_end=328, 43 | ) 44 | 45 | 46 | _TESTMESSAGE_MSGITEM = _descriptor.Descriptor( 47 | name='MsgItem', 48 | full_name='ProtobufTest.TestMessage.MsgItem', 49 | filename=None, 50 | file=DESCRIPTOR, 51 | containing_type=None, 52 | fields=[ 53 | _descriptor.FieldDescriptor( 54 | name='id', full_name='ProtobufTest.TestMessage.MsgItem.id', index=0, 55 | number=1, type=5, cpp_type=1, label=2, 56 | has_default_value=False, default_value=0, 57 | message_type=None, enum_type=None, containing_type=None, 58 | is_extension=False, extension_scope=None, 59 | options=None), 60 | _descriptor.FieldDescriptor( 61 | name='itemName', full_name='ProtobufTest.TestMessage.MsgItem.itemName', index=1, 62 | number=2, type=9, cpp_type=9, label=1, 63 | has_default_value=False, default_value=unicode("", "utf-8"), 64 | message_type=None, enum_type=None, containing_type=None, 65 | is_extension=False, extension_scope=None, 66 | options=None), 67 | _descriptor.FieldDescriptor( 68 | name='itemValue', full_name='ProtobufTest.TestMessage.MsgItem.itemValue', index=2, 69 | number=3, type=5, cpp_type=1, label=1, 70 | has_default_value=False, default_value=0, 71 | message_type=None, enum_type=None, containing_type=None, 72 | is_extension=False, extension_scope=None, 73 | options=None), 74 | _descriptor.FieldDescriptor( 75 | name='itemType', full_name='ProtobufTest.TestMessage.MsgItem.itemType', index=3, 76 | number=4, type=14, cpp_type=8, label=1, 77 | has_default_value=False, default_value=0, 78 | message_type=None, enum_type=None, containing_type=None, 79 | is_extension=False, extension_scope=None, 80 | options=None), 81 | ], 82 | extensions=[ 83 | ], 84 | nested_types=[], 85 | enum_types=[ 86 | ], 87 | options=None, 88 | is_extendable=False, 89 | extension_ranges=[], 90 | serialized_start=171, 91 | serialized_end=283, 92 | ) 93 | 94 | _TESTMESSAGE = _descriptor.Descriptor( 95 | name='TestMessage', 96 | full_name='ProtobufTest.TestMessage', 97 | filename=None, 98 | file=DESCRIPTOR, 99 | containing_type=None, 100 | fields=[ 101 | _descriptor.FieldDescriptor( 102 | name='clientName', full_name='ProtobufTest.TestMessage.clientName', index=0, 103 | number=1, type=9, cpp_type=9, label=2, 104 | has_default_value=False, default_value=unicode("", "utf-8"), 105 | message_type=None, enum_type=None, containing_type=None, 106 | is_extension=False, extension_scope=None, 107 | options=None), 108 | _descriptor.FieldDescriptor( 109 | name='clientId', full_name='ProtobufTest.TestMessage.clientId', index=1, 110 | number=2, type=5, cpp_type=1, label=2, 111 | has_default_value=False, default_value=0, 112 | message_type=None, enum_type=None, containing_type=None, 113 | is_extension=False, extension_scope=None, 114 | options=None), 115 | _descriptor.FieldDescriptor( 116 | name='description', full_name='ProtobufTest.TestMessage.description', index=2, 117 | number=3, type=9, cpp_type=9, label=1, 118 | has_default_value=True, default_value=unicode("NONE", "utf-8"), 119 | message_type=None, enum_type=None, containing_type=None, 120 | is_extension=False, extension_scope=None, 121 | options=None), 122 | _descriptor.FieldDescriptor( 123 | name='messageitems', full_name='ProtobufTest.TestMessage.messageitems', index=3, 124 | number=4, type=11, cpp_type=10, label=3, 125 | has_default_value=False, default_value=[], 126 | message_type=None, enum_type=None, containing_type=None, 127 | is_extension=False, extension_scope=None, 128 | options=None), 129 | ], 130 | extensions=[ 131 | ], 132 | nested_types=[_TESTMESSAGE_MSGITEM, ], 133 | enum_types=[ 134 | _TESTMESSAGE_ITEMTYPE, 135 | ], 136 | options=None, 137 | is_extendable=False, 138 | extension_ranges=[], 139 | serialized_start=34, 140 | serialized_end=328, 141 | ) 142 | 143 | _TESTMESSAGE_MSGITEM.fields_by_name['itemType'].enum_type = _TESTMESSAGE_ITEMTYPE 144 | _TESTMESSAGE_MSGITEM.containing_type = _TESTMESSAGE; 145 | _TESTMESSAGE.fields_by_name['messageitems'].message_type = _TESTMESSAGE_MSGITEM 146 | _TESTMESSAGE_ITEMTYPE.containing_type = _TESTMESSAGE; 147 | DESCRIPTOR.message_types_by_name['TestMessage'] = _TESTMESSAGE 148 | 149 | class TestMessage(_message.Message): 150 | __metaclass__ = _reflection.GeneratedProtocolMessageType 151 | 152 | class MsgItem(_message.Message): 153 | __metaclass__ = _reflection.GeneratedProtocolMessageType 154 | DESCRIPTOR = _TESTMESSAGE_MSGITEM 155 | 156 | # @@protoc_insertion_point(class_scope:ProtobufTest.TestMessage.MsgItem) 157 | DESCRIPTOR = _TESTMESSAGE 158 | 159 | # @@protoc_insertion_point(class_scope:ProtobufTest.TestMessage) 160 | 161 | 162 | # @@protoc_insertion_point(module_scope) 163 | -------------------------------------------------------------------------------- /PythonProtobufClient/ProtoTest_pb2.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/minaandrawos/Go-Protobuf-Examples/e11f46ed2b4347449f8f6f4d4d1a89c82fd49c79/PythonProtobufClient/ProtoTest_pb2.pyc -------------------------------------------------------------------------------- /PythonProtobufClient/PyProtoClient.py: -------------------------------------------------------------------------------- 1 | from optparse import OptionParser 2 | import ProtoTest_pb2 3 | import csv 4 | import socket 5 | 6 | CLIENT_NAME = 'PyClient' 7 | CLIENT_ID = 1 8 | CLIENT_DESCRIPTION = 'This is a Python script!!' 9 | 10 | def RetrieveMessagesValuesFromFile(filename): 11 | if filename=='': 12 | print "Error: No File Name Specified" 13 | return 14 | with open(filename ,'r') as f: 15 | csvreader = csv.reader(f, delimiter=',') 16 | header = next(csvreader, None) 17 | print "Headers:", header 18 | 19 | MessageToSend = ProtoTest_pb2.TestMessage() 20 | MessageToSend.clientId = CLIENT_ID 21 | MessageToSend.clientName = CLIENT_NAME 22 | MessageToSend.description = CLIENT_DESCRIPTION 23 | 24 | for row in csvreader: 25 | print row 26 | try: 27 | Item = MessageToSend.messageitems.add() 28 | Item.id = int(row[header.index('itemid')]) 29 | Item.itemName = row[header.index('itemname')] 30 | Item.itemValue = int(row[header.index('itemvalue')]) 31 | Item.itemType = int(row[header.index('itemType')]) 32 | 33 | except Exception, e: 34 | print "Error %s occured while parsing message data from the csv file, please double check the input file" % str(e) 35 | 36 | print "Number of items in message to send", str(len(MessageToSend.messageitems)) 37 | 38 | return MessageToSend.SerializeToString() 39 | 40 | def SendProtoMessage(protomessage , dstadress): 41 | addresssplit = str(dstadress).split(':') 42 | if len(addresssplit)>2: 43 | print "Invalid destination address" 44 | try: 45 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 46 | s.connect((addresssplit[0], int(addresssplit[1]))) 47 | s.send(protomessage) 48 | except Exception, e: 49 | print "Error %s occured while attempting to send data" % str(e) 50 | finally: 51 | s.close() 52 | 53 | 54 | 55 | 56 | 57 | if __name__ == "__main__": 58 | parser = OptionParser() 59 | parser.add_option('-d', help='specify tcp server', default='127.0.0.1:2110', action='store') 60 | parser.add_option('-f', help='CSV file name where the data exists', default='CSVValues.csv', action='store') 61 | (options, args) = parser.parse_args() 62 | serializedmessage = RetrieveMessagesValuesFromFile(options.f) 63 | SendProtoMessage(serializedmessage, options.d) 64 | 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Go-Protobuf-Examples 2 | ==================== 3 | 4 | A protocol buffer (Protobuf) server and client in Go (Golang) 5 | 6 | A detailed tutorial can be found at: www.minaandrawos.com/2014/05/27/practical-guide-protocol-buffers-protobuf-go-golang/ 7 | 8 | I wrote this code as part of a tutorial on how to practically use Protocol buffer in Go (Golang), the code is organized as follows: 9 | 10 | 1. /src/GoProtoClient --> The Golang Protobuf client code 11 | 2. /src/GoProtoServer --> The Golang Protobuf server code 12 | 3. /src/ProtobufTest --> The compiled Protocol buffer file for this project 13 | 4. PythonProtobufClient --> An implementation of the same protobuf client using Python 14 | 15 | A detailed tutorial will follow in my website when I am done polishing it, however for the time being, here is a brief outline for what you need to try out the example code: 16 | 17 | 1. Get Go: http://golang.org/doc/install 18 | 2. Get GoProtobuf: https://code.google.com/p/goprotobuf/ 19 | 3. Get Python 20 | 4. Get protobuf for Python 21 | 5. Get the code from here, probably use the "go get" command http://golang.org/cmd/go/ 22 | 6. You can either use the source file that I already compiled from the .proto file directly or you can compile them again yourself using protobuf command tool. 23 | 7. Play around with the code and enjoy 24 | 25 | This code is for education purposes , use at your own risk , you can change it and play with it as much as you want. 26 | 27 | -------------------------------------------------------------------------------- /bin/CSVValue.csv: -------------------------------------------------------------------------------- 1 | itemid,itemname,itemvalue,itemType 2 | 1,FirstItemName,777,0 3 | 2,SecondItemName,888,1 4 | 3,ThirdItemName,999,2 5 | 4,FourthItemName,1010,0 6 | 5,FifthItemName,2020,3 7 | -------------------------------------------------------------------------------- /bin/CSVValues.csv: -------------------------------------------------------------------------------- 1 | ClientID,ClientName,ClientDescription,ItemId,ItemName,ItemValue,ItemType 2 | 2,GoClient,This is a Go Protobuf client!!,1,FirstItemName,777,0 3 | 2,GoClient,This is a Go Protobuf client!!,2,SecondItemName,888,1 4 | 2,GoClient,This is a Go Protobuf client!!,3,ThirdItemName,999,2 5 | 2,GoClient,This is a Go Protobuf client!!,4,FourthItemName,1010,0 6 | 2,GoClient,This is a Go Protobuf client!!,5,FifthItemName,2020,3 7 | ClientID,ClientName,ClientDescription,ItemId,ItemName,ItemValue,ItemType 8 | 2,GoClient,This is a Go Protobuf client!!,1,FirstItemName,777,0 9 | 2,GoClient,This is a Go Protobuf client!!,2,SecondItemName,888,1 10 | 2,GoClient,This is a Go Protobuf client!!,3,ThirdItemName,999,2 11 | 2,GoClient,This is a Go Protobuf client!!,4,FourthItemName,1010,0 12 | 2,GoClient,This is a Go Protobuf client!!,5,FifthItemName,2020,3 13 | ClientID,ClientName,ClientDescription,ItemId,ItemName,ItemValue,ItemType 14 | 2,GoClient,This is a Go Protobuf client!!,1,FirstItemName,777,0 15 | 2,GoClient,This is a Go Protobuf client!!,2,SecondItemName,888,1 16 | 2,GoClient,This is a Go Protobuf client!!,3,ThirdItemName,999,2 17 | 2,GoClient,This is a Go Protobuf client!!,4,FourthItemName,1010,0 18 | 2,GoClient,This is a Go Protobuf client!!,5,FifthItemName,2020,3 19 | ClientID,ClientName,ClientDescription,ItemId,ItemName,ItemValue,ItemType 20 | 1,PyClient,This is a Python script!!,1,FirstItemName,222,0 21 | 1,PyClient,This is a Python script!!,2,SecondItemName,333,1 22 | 1,PyClient,This is a Python script!!,3,ThirdItemName,444,2 23 | 1,PyClient,This is a Python script!!,4,FourthItemName,555,0 24 | 1,PyClient,This is a Python script!!,5,FifthItemName,666,3 25 | ClientID,ClientName,ClientDescription,ItemId,ItemName,ItemValue,ItemType 26 | 2,GoClient,This is a Go Protobuf client!!,1,FirstItemName,777,0 27 | 2,GoClient,This is a Go Protobuf client!!,2,SecondItemName,888,1 28 | 2,GoClient,This is a Go Protobuf client!!,3,ThirdItemName,999,2 29 | 2,GoClient,This is a Go Protobuf client!!,4,FourthItemName,1010,0 30 | 2,GoClient,This is a Go Protobuf client!!,5,FifthItemName,2020,3 31 | ClientID,ClientName,ClientDescription,ItemId,ItemName,ItemValue,ItemType 32 | 1,PyClient,This is a Python script!!,1,FirstItemName,222,0 33 | 1,PyClient,This is a Python script!!,2,SecondItemName,333,1 34 | 1,PyClient,This is a Python script!!,3,ThirdItemName,444,2 35 | 1,PyClient,This is a Python script!!,4,FourthItemName,555,0 36 | 1,PyClient,This is a Python script!!,5,FifthItemName,666,3 37 | ClientID,ClientName,ClientDescription,ItemId,ItemName,ItemValue,ItemType 38 | 1,PyClient,This is a Python script!!,1,FirstItemName,222,0 39 | 1,PyClient,This is a Python script!!,2,SecondItemName,333,1 40 | 1,PyClient,This is a Python script!!,3,ThirdItemName,444,2 41 | 1,PyClient,This is a Python script!!,4,FourthItemName,555,0 42 | 1,PyClient,This is a Python script!!,5,FifthItemName,666,3 43 | ClientID,ClientName,ClientDescription,ItemId,ItemName,ItemValue,ItemType 44 | 2,GoClient,This is a Go Protobuf client!!,1,FirstItemName,777,0 45 | 2,GoClient,This is a Go Protobuf client!!,2,SecondItemName,888,1 46 | 2,GoClient,This is a Go Protobuf client!!,3,ThirdItemName,999,2 47 | 2,GoClient,This is a Go Protobuf client!!,4,FourthItemName,1010,0 48 | 2,GoClient,This is a Go Protobuf client!!,5,FifthItemName,2020,3 49 | 2,GoClient,This is a Go Protobuf client!!,1,FirstItemName,777,0 50 | 2,GoClient,This is a Go Protobuf client!!,2,SecondItemName,888,1 51 | 2,GoClient,This is a Go Protobuf client!!,3,ThirdItemName,999,2 52 | 2,GoClient,This is a Go Protobuf client!!,4,FourthItemName,1010,0 53 | 2,GoClient,This is a Go Protobuf client!!,5,FifthItemName,2020,3 54 | -------------------------------------------------------------------------------- /pkg/windows_386/ProtobufTest.a: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/minaandrawos/Go-Protobuf-Examples/e11f46ed2b4347449f8f6f4d4d1a89c82fd49c79/pkg/windows_386/ProtobufTest.a -------------------------------------------------------------------------------- /pkg/windows_amd64/ProtobufTest.a: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/minaandrawos/Go-Protobuf-Examples/e11f46ed2b4347449f8f6f4d4d1a89c82fd49c79/pkg/windows_amd64/ProtobufTest.a -------------------------------------------------------------------------------- /src/GoProtoClient/CSVV.csv: -------------------------------------------------------------------------------- 1 | itemid,itemname,itemvalue,itemType 2 | 1,FirstItemName,222,0 3 | 2,SecondItemName,333,1 4 | 3,ThirdItemName,444,2 5 | 4,FourthItemName,555,0 6 | 5,FifthItemName,666,3 7 | -------------------------------------------------------------------------------- /src/GoProtoClient/GoProtoClient.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "ProtobufTest" 5 | "code.google.com/p/goprotobuf/proto" 6 | "net" 7 | "os" 8 | "encoding/csv" 9 | "flag" 10 | "io" 11 | "strconv" 12 | "fmt" 13 | ) 14 | 15 | type Headers []string 16 | const CLIENT_NAME = "GoClient" 17 | const CLIENT_ID = 2 18 | const CLIENT_DESCRIPTION = "This is a Go Protobuf client!!" 19 | 20 | func main() { 21 | filename := flag.String("f","CSVValue.csv","Enter the filename to read from") 22 | dest := flag.String("d","127.0.0.1:2110","Enter the destnation socket address") 23 | flag.Parse() 24 | data, err := retrieveDataFromFile(filename) 25 | checkError(err) 26 | sendDataToDest(data, dest) 27 | } 28 | 29 | func retrieveDataFromFile(fname *string)([]byte,error ){ 30 | file, err := os.Open(*fname) 31 | checkError(err) 32 | defer file.Close() 33 | 34 | csvreader := csv.NewReader(file) 35 | var hdrs Headers 36 | hdrs, err = csvreader.Read() 37 | checkError(err) 38 | ITEMIDINDEX := hdrs.getHeaderIndex("itemid") 39 | ITEMNAMEINDEX := hdrs.getHeaderIndex("itemname") 40 | ITEMVALUEINDEX := hdrs.getHeaderIndex("itemvalue") 41 | ITEMTYPEINDEX := hdrs.getHeaderIndex("itemType") 42 | 43 | ProtoMessage:= new(ProtobufTest.TestMessage) 44 | ProtoMessage.ClientName = proto.String(CLIENT_NAME) 45 | ProtoMessage.ClientId = proto.Int32(CLIENT_ID) 46 | ProtoMessage.Description = proto.String(CLIENT_DESCRIPTION) 47 | 48 | //loop through the records 49 | for{ 50 | record, err := csvreader.Read() 51 | if(err!=io.EOF) { 52 | checkError(err) 53 | }else{ 54 | 55 | break 56 | } 57 | //Populate items 58 | testMessageItem:= new(ProtobufTest.TestMessage_MsgItem) 59 | itemid,err := strconv.Atoi(record[ITEMIDINDEX]) 60 | checkError(err) 61 | testMessageItem.Id = proto.Int32(int32(itemid)) 62 | testMessageItem.ItemName = &record[ITEMNAMEINDEX] 63 | itemvalue,err:= strconv.Atoi(record[ITEMVALUEINDEX]) 64 | checkError(err) 65 | testMessageItem.ItemValue = proto.Int32(int32(itemvalue)) 66 | itemtype,err := strconv.Atoi(record[ITEMTYPEINDEX]) 67 | checkError(err) 68 | iType := ProtobufTest.TestMessage_ItemType(itemtype) 69 | testMessageItem.ItemType = &iType 70 | 71 | ProtoMessage.Messageitems = append(ProtoMessage.Messageitems, testMessageItem) 72 | 73 | fmt.Println(record) 74 | } 75 | 76 | //fmt.Println(ProtoMessage.Messageitems) 77 | return proto.Marshal(ProtoMessage) 78 | } 79 | 80 | func sendDataToDest(data []byte, dst *string){ 81 | conn,err := net.Dial("tcp",*dst) 82 | checkError(err) 83 | n,err := conn.Write(data) 84 | checkError(err) 85 | fmt.Println("Sent " + strconv.Itoa(n) + " bytes") 86 | } 87 | 88 | func checkError(err error){ 89 | if err != nil { 90 | fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error()) 91 | os.Exit(1) 92 | } 93 | } 94 | 95 | func (h Headers) getHeaderIndex(headername string) int { 96 | if len(headername)>=2{ 97 | for index, s := range h{ 98 | if s == headername{ 99 | return index 100 | } 101 | } 102 | } 103 | return -1 104 | } 105 | -------------------------------------------------------------------------------- /src/GoProtoServer/GoProtoServer.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "code.google.com/p/goprotobuf/proto" 6 | "net" 7 | "os" 8 | "ProtobufTest" 9 | "encoding/csv" 10 | "strconv" 11 | ) 12 | 13 | func main() { 14 | fmt.Printf("Started ProtoBuf Server") 15 | c := make(chan *ProtobufTest.TestMessage) 16 | go func(){ 17 | for{ 18 | message := <-c 19 | writeValuesTofile(message) 20 | 21 | } 22 | }() 23 | //Listen to the TCP port 24 | listener, err := net.Listen("tcp", "127.0.0.1:2110") 25 | checkError(err) 26 | for{ 27 | if conn, err := listener.Accept(); err == nil{ 28 | //If err is nil then that means that data is available for us so we take up this data and pass it to a new goroutine 29 | go handleProtoClient(conn, c) 30 | } else{ 31 | continue 32 | } 33 | } 34 | } 35 | 36 | func handleProtoClient(conn net.Conn, c chan *ProtobufTest.TestMessage){ 37 | fmt.Println("Connection established") 38 | //Close the connection when the function exits 39 | defer conn.Close() 40 | //Create a data buffer of type byte slice with capacity of 4096 41 | data := make([]byte, 4096) 42 | //Read the data waiting on the connection and put it in the data buffer 43 | n,err:= conn.Read(data) 44 | checkError(err) 45 | fmt.Println("Decoding Protobuf message") 46 | //Create an struct pointer of type ProtobufTest.TestMessage struct 47 | protodata := new(ProtobufTest.TestMessage) 48 | //Convert all the data retrieved into the ProtobufTest.TestMessage struct type 49 | err = proto.Unmarshal(data[0:n], protodata) 50 | checkError(err) 51 | //Push the protobuf message into a channel 52 | c <- protodata 53 | } 54 | 55 | func writeValuesTofile(datatowrite *ProtobufTest.TestMessage){ 56 | 57 | //Retreive client information from the protobuf message 58 | ClientName := datatowrite.GetClientName() 59 | ClientDescription := datatowrite.GetDescription() 60 | ClientID := strconv.Itoa(int(datatowrite.GetClientId())) 61 | 62 | // retrieve the message items list 63 | items := datatowrite.GetMessageitems() 64 | fmt.Println("Writing value to CSV file") 65 | //Open file for writes, if the file does not exist then create it 66 | file,err := os.OpenFile("CSVValues.csv", os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666) 67 | checkError(err) 68 | //make sure the file gets closed once the function exists 69 | defer file.Close() 70 | //Go through the list of message items, insert them into a string array then write them to the CSV file. 71 | writer := csv.NewWriter(file) 72 | for _,item := range items{ 73 | record := []string{ClientID, ClientName, ClientDescription, strconv.Itoa(int(item.GetId())), item.GetItemName(), strconv.Itoa(int(item.GetItemValue())),strconv.Itoa(int(item.GetItemType()))} 74 | writer.Write(record) 75 | fmt.Println(record) 76 | } 77 | //flush data to the CSV file 78 | writer.Flush() 79 | fmt.Println("Finished Writing value to CSV file") 80 | } 81 | 82 | func checkError(err error){ 83 | if err != nil { 84 | fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error()) 85 | os.Exit(1) 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/ProtoTest.proto: -------------------------------------------------------------------------------- 1 | package ProtobufTest; 2 | 3 | message TestMessage { 4 | required string clientName = 1; 5 | required int32 clientId = 2; 6 | optional string description = 3 [default = "NONE"]; 7 | repeated MsgItem messageitems = 4; 8 | 9 | enum ItemType { 10 | TypeX = 0; 11 | TypeY = 1; 12 | TypeZ = 2; 13 | } 14 | 15 | message MsgItem { 16 | required int32 id = 1; 17 | optional string itemName = 2; 18 | optional int32 itemValue = 3; 19 | optional ItemType itemType = 4; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/ProtobufTest/ProtoTest.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. 2 | // source: ProtobufTest.proto 3 | // DO NOT EDIT! 4 | 5 | /* 6 | Package ProtobufTest is a generated protocol buffer package. 7 | 8 | It is generated from these files: 9 | ProtobufTest.proto 10 | 11 | It has these top-level messages: 12 | TestMessage 13 | */ 14 | package ProtobufTest 15 | 16 | import proto "code.google.com/p/goprotobuf/proto" 17 | import math "math" 18 | 19 | // Reference imports to suppress errors if they are not otherwise used. 20 | var _ = proto.Marshal 21 | var _ = math.Inf 22 | 23 | type TestMessage_ItemType int32 24 | 25 | const ( 26 | TestMessage_TypeX TestMessage_ItemType = 0 27 | TestMessage_TypeY TestMessage_ItemType = 1 28 | TestMessage_TypeZ TestMessage_ItemType = 2 29 | ) 30 | 31 | var TestMessage_ItemType_name = map[int32]string{ 32 | 0: "TypeX", 33 | 1: "TypeY", 34 | 2: "TypeZ", 35 | } 36 | var TestMessage_ItemType_value = map[string]int32{ 37 | "TypeX": 0, 38 | "TypeY": 1, 39 | "TypeZ": 2, 40 | } 41 | 42 | func (x TestMessage_ItemType) Enum() *TestMessage_ItemType { 43 | p := new(TestMessage_ItemType) 44 | *p = x 45 | return p 46 | } 47 | func (x TestMessage_ItemType) String() string { 48 | return proto.EnumName(TestMessage_ItemType_name, int32(x)) 49 | } 50 | func (x *TestMessage_ItemType) UnmarshalJSON(data []byte) error { 51 | value, err := proto.UnmarshalJSONEnum(TestMessage_ItemType_value, data, "TestMessage_ItemType") 52 | if err != nil { 53 | return err 54 | } 55 | *x = TestMessage_ItemType(value) 56 | return nil 57 | } 58 | 59 | type TestMessage struct { 60 | ClientName *string `protobuf:"bytes,1,req,name=clientName" json:"clientName,omitempty"` 61 | ClientId *int32 `protobuf:"varint,2,req,name=clientId" json:"clientId,omitempty"` 62 | Description *string `protobuf:"bytes,3,opt,name=description,def=NONE" json:"description,omitempty"` 63 | Messageitems []*TestMessage_MsgItem `protobuf:"bytes,4,rep,name=messageitems" json:"messageitems,omitempty"` 64 | XXX_unrecognized []byte `json:"-"` 65 | } 66 | 67 | func (m *TestMessage) Reset() { *m = TestMessage{} } 68 | func (m *TestMessage) String() string { return proto.CompactTextString(m) } 69 | func (*TestMessage) ProtoMessage() {} 70 | 71 | const Default_TestMessage_Description string = "NONE" 72 | 73 | func (m *TestMessage) GetClientName() string { 74 | if m != nil && m.ClientName != nil { 75 | return *m.ClientName 76 | } 77 | return "" 78 | } 79 | 80 | func (m *TestMessage) GetClientId() int32 { 81 | if m != nil && m.ClientId != nil { 82 | return *m.ClientId 83 | } 84 | return 0 85 | } 86 | 87 | func (m *TestMessage) GetDescription() string { 88 | if m != nil && m.Description != nil { 89 | return *m.Description 90 | } 91 | return Default_TestMessage_Description 92 | } 93 | 94 | func (m *TestMessage) GetMessageitems() []*TestMessage_MsgItem { 95 | if m != nil { 96 | return m.Messageitems 97 | } 98 | return nil 99 | } 100 | 101 | type TestMessage_MsgItem struct { 102 | Id *int32 `protobuf:"varint,1,req,name=id" json:"id,omitempty"` 103 | ItemName *string `protobuf:"bytes,2,opt,name=itemName" json:"itemName,omitempty"` 104 | ItemValue *int32 `protobuf:"varint,3,opt,name=itemValue" json:"itemValue,omitempty"` 105 | ItemType *TestMessage_ItemType `protobuf:"varint,4,opt,name=itemType,enum=ProtobufTest.TestMessage_ItemType" json:"itemType,omitempty"` 106 | XXX_unrecognized []byte `json:"-"` 107 | } 108 | 109 | func (m *TestMessage_MsgItem) Reset() { *m = TestMessage_MsgItem{} } 110 | func (m *TestMessage_MsgItem) String() string { return proto.CompactTextString(m) } 111 | func (*TestMessage_MsgItem) ProtoMessage() {} 112 | 113 | func (m *TestMessage_MsgItem) GetId() int32 { 114 | if m != nil && m.Id != nil { 115 | return *m.Id 116 | } 117 | return 0 118 | } 119 | 120 | func (m *TestMessage_MsgItem) GetItemName() string { 121 | if m != nil && m.ItemName != nil { 122 | return *m.ItemName 123 | } 124 | return "" 125 | } 126 | 127 | func (m *TestMessage_MsgItem) GetItemValue() int32 { 128 | if m != nil && m.ItemValue != nil { 129 | return *m.ItemValue 130 | } 131 | return 0 132 | } 133 | 134 | func (m *TestMessage_MsgItem) GetItemType() TestMessage_ItemType { 135 | if m != nil && m.ItemType != nil { 136 | return *m.ItemType 137 | } 138 | return TestMessage_TypeX 139 | } 140 | 141 | func init() { 142 | proto.RegisterEnum("ProtobufTest.TestMessage_ItemType", TestMessage_ItemType_name, TestMessage_ItemType_value) 143 | } 144 | --------------------------------------------------------------------------------