Skip to content

Commit eec0f66

Browse files
committed
add protobuf_examples
1 parent 140ec6f commit eec0f66

15 files changed

+1022
-0
lines changed

unity_protobuf_sample/README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,9 @@ protobuf_tools
3838
build_server_protobuf.bat(自动生成proto服务器代码)
3939

4040
</pre>
41+
42+
43+
44+
### protobuf_examples
45+
46+
protobuf_examples目录是从google官方checkout的example https://github.com/google/protobuf/trunk/examples
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
// See README.txt for information and build instructions.
2+
3+
import com.example.tutorial.AddressBookProtos.AddressBook;
4+
import com.example.tutorial.AddressBookProtos.Person;
5+
import java.io.BufferedReader;
6+
import java.io.FileInputStream;
7+
import java.io.FileNotFoundException;
8+
import java.io.FileOutputStream;
9+
import java.io.InputStreamReader;
10+
import java.io.IOException;
11+
import java.io.PrintStream;
12+
13+
class AddPerson {
14+
// This function fills in a Person message based on user input.
15+
static Person PromptForAddress(BufferedReader stdin,
16+
PrintStream stdout) throws IOException {
17+
Person.Builder person = Person.newBuilder();
18+
19+
stdout.print("Enter person ID: ");
20+
person.setId(Integer.valueOf(stdin.readLine()));
21+
22+
stdout.print("Enter name: ");
23+
person.setName(stdin.readLine());
24+
25+
stdout.print("Enter email address (blank for none): ");
26+
String email = stdin.readLine();
27+
if (email.length() > 0) {
28+
person.setEmail(email);
29+
}
30+
31+
while (true) {
32+
stdout.print("Enter a phone number (or leave blank to finish): ");
33+
String number = stdin.readLine();
34+
if (number.length() == 0) {
35+
break;
36+
}
37+
38+
Person.PhoneNumber.Builder phoneNumber =
39+
Person.PhoneNumber.newBuilder().setNumber(number);
40+
41+
stdout.print("Is this a mobile, home, or work phone? ");
42+
String type = stdin.readLine();
43+
if (type.equals("mobile")) {
44+
phoneNumber.setType(Person.PhoneType.MOBILE);
45+
} else if (type.equals("home")) {
46+
phoneNumber.setType(Person.PhoneType.HOME);
47+
} else if (type.equals("work")) {
48+
phoneNumber.setType(Person.PhoneType.WORK);
49+
} else {
50+
stdout.println("Unknown phone type. Using default.");
51+
}
52+
53+
person.addPhones(phoneNumber);
54+
}
55+
56+
return person.build();
57+
}
58+
59+
// Main function: Reads the entire address book from a file,
60+
// adds one person based on user input, then writes it back out to the same
61+
// file.
62+
public static void main(String[] args) throws Exception {
63+
if (args.length != 1) {
64+
System.err.println("Usage: AddPerson ADDRESS_BOOK_FILE");
65+
System.exit(-1);
66+
}
67+
68+
AddressBook.Builder addressBook = AddressBook.newBuilder();
69+
70+
// Read the existing address book.
71+
try {
72+
FileInputStream input = new FileInputStream(args[0]);
73+
try {
74+
addressBook.mergeFrom(input);
75+
} finally {
76+
try { input.close(); } catch (Throwable ignore) {}
77+
}
78+
} catch (FileNotFoundException e) {
79+
System.out.println(args[0] + ": File not found. Creating a new file.");
80+
}
81+
82+
// Add an address.
83+
addressBook.addPeople(
84+
PromptForAddress(new BufferedReader(new InputStreamReader(System.in)),
85+
System.out));
86+
87+
// Write the new address book back to disk.
88+
FileOutputStream output = new FileOutputStream(args[0]);
89+
try {
90+
addressBook.build().writeTo(output);
91+
} finally {
92+
output.close();
93+
}
94+
}
95+
}
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# Minimum CMake required
2+
cmake_minimum_required(VERSION 2.8.12)
3+
4+
# Project
5+
project(protobuf-examples)
6+
7+
# Find required protobuf package
8+
find_package(protobuf CONFIG REQUIRED)
9+
10+
if(protobuf_VERBOSE)
11+
message(STATUS "Using Protocol Buffers ${Protobuf_VERSION}")
12+
endif()
13+
14+
set(CMAKE_INCLUDE_CURRENT_DIR TRUE)
15+
16+
# http://www.cmake.org/Wiki/CMake_FAQ#How_can_I_build_my_MSVC_application_with_a_static_runtime.3F
17+
if(MSVC AND protobuf_MSVC_STATIC_RUNTIME)
18+
foreach(flag_var
19+
CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE
20+
CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)
21+
if(${flag_var} MATCHES "/MD")
22+
string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}")
23+
endif(${flag_var} MATCHES "/MD")
24+
endforeach()
25+
endif()
26+
27+
foreach(example add_person list_people)
28+
set(${example}_SRCS ${example}.cc)
29+
set(${example}_PROTOS addressbook.proto)
30+
31+
#Code Generation
32+
if(protobuf_MODULE_COMPATIBLE) #Legacy Support
33+
protobuf_generate_cpp(${example}_PROTO_SRCS ${example}_PROTO_HDRS ${${example}_PROTOS})
34+
list(APPEND ${example}_SRCS ${${example}_PROTO_SRCS} ${${example}_PROTO_HDRS})
35+
else()
36+
37+
foreach(proto_file ${${example}_PROTOS})
38+
get_filename_component(proto_file_abs ${proto_file} ABSOLUTE)
39+
get_filename_component(basename ${proto_file} NAME_WE)
40+
set(generated_files ${basename}.pb.cc ${basename}.pb.h)
41+
list(APPEND ${example}_SRCS ${generated_files})
42+
43+
add_custom_command(
44+
OUTPUT ${generated_files}
45+
COMMAND protobuf::protoc
46+
ARGS --cpp_out ${CMAKE_CURRENT_BINARY_DIR} -I ${CMAKE_CURRENT_SOURCE_DIR} ${proto_file_abs}
47+
COMMENT "Generating ${generated_files} from ${proto_file}"
48+
VERBATIM
49+
)
50+
endforeach()
51+
endif()
52+
53+
#Executable setup
54+
set(executable_name ${example}_cpp)
55+
add_executable(${executable_name} ${${example}_SRCS} ${${example}_PROTOS})
56+
if(protobuf_MODULE_COMPATIBLE) #Legacy mode
57+
target_include_directories(${executable_name} PUBLIC ${PROTOBUF_INCLUDE_DIRS})
58+
target_link_libraries(${executable_name} ${PROTOBUF_LIBRARIES})
59+
else()
60+
target_link_libraries(${executable_name} protobuf::libprotobuf)
61+
endif()
62+
63+
endforeach()
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// See README.txt for information and build instructions.
2+
3+
import com.example.tutorial.AddressBookProtos.AddressBook;
4+
import com.example.tutorial.AddressBookProtos.Person;
5+
import java.io.FileInputStream;
6+
import java.io.IOException;
7+
import java.io.PrintStream;
8+
9+
class ListPeople {
10+
// Iterates though all people in the AddressBook and prints info about them.
11+
static void Print(AddressBook addressBook) {
12+
for (Person person: addressBook.getPeopleList()) {
13+
System.out.println("Person ID: " + person.getId());
14+
System.out.println(" Name: " + person.getName());
15+
if (!person.getEmail().isEmpty()) {
16+
System.out.println(" E-mail address: " + person.getEmail());
17+
}
18+
19+
for (Person.PhoneNumber phoneNumber : person.getPhonesList()) {
20+
switch (phoneNumber.getType()) {
21+
case MOBILE:
22+
System.out.print(" Mobile phone #: ");
23+
break;
24+
case HOME:
25+
System.out.print(" Home phone #: ");
26+
break;
27+
case WORK:
28+
System.out.print(" Work phone #: ");
29+
break;
30+
}
31+
System.out.println(phoneNumber.getNumber());
32+
}
33+
}
34+
}
35+
36+
// Main function: Reads the entire address book from a file and prints all
37+
// the information inside.
38+
public static void main(String[] args) throws Exception {
39+
if (args.length != 1) {
40+
System.err.println("Usage: ListPeople ADDRESS_BOOK_FILE");
41+
System.exit(-1);
42+
}
43+
44+
// Read the existing address book.
45+
AddressBook addressBook =
46+
AddressBook.parseFrom(new FileInputStream(args[0]));
47+
48+
Print(addressBook);
49+
}
50+
}
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
# See README.txt.
2+
3+
.PHONY: all cpp java python clean
4+
5+
all: cpp java python
6+
7+
cpp: add_person_cpp list_people_cpp
8+
go: add_person_go list_people_go
9+
gotest: add_person_gotest list_people_gotest
10+
java: add_person_java list_people_java
11+
python: add_person_python list_people_python
12+
13+
clean:
14+
rm -f add_person_cpp list_people_cpp add_person_java list_people_java add_person_python list_people_python
15+
rm -f javac_middleman AddPerson*.class ListPeople*.class com/example/tutorial/*.class
16+
rm -f protoc_middleman addressbook.pb.cc addressbook.pb.h addressbook_pb2.py com/example/tutorial/AddressBookProtos.java
17+
rm -f *.pyc
18+
rm -f protoc_middleman_go tutorial/*.pb.go add_person_go list_people_go
19+
rmdir tutorial 2>/dev/null || true
20+
rmdir com/example/tutorial 2>/dev/null || true
21+
rmdir com/example 2>/dev/null || true
22+
rmdir com 2>/dev/null || true
23+
24+
protoc_middleman: addressbook.proto
25+
protoc --cpp_out=. --java_out=. --python_out=. addressbook.proto
26+
@touch protoc_middleman
27+
28+
protoc_middleman_go: addressbook.proto
29+
mkdir tutorial # make directory for go package
30+
protoc --go_out=tutorial addressbook.proto
31+
@touch protoc_middleman_go
32+
33+
add_person_cpp: add_person.cc protoc_middleman
34+
pkg-config --cflags protobuf # fails if protobuf is not installed
35+
c++ add_person.cc addressbook.pb.cc -o add_person_cpp `pkg-config --cflags --libs protobuf`
36+
37+
list_people_cpp: list_people.cc protoc_middleman
38+
pkg-config --cflags protobuf # fails if protobuf is not installed
39+
c++ list_people.cc addressbook.pb.cc -o list_people_cpp `pkg-config --cflags --libs protobuf`
40+
41+
add_person_go: add_person.go protoc_middleman_go
42+
go build -o add_person_go add_person.go
43+
44+
add_person_gotest: add_person_test.go add_person_go
45+
go test add_person.go add_person_test.go
46+
47+
list_people_go: list_people.go protoc_middleman_go
48+
go build -o list_people_go list_people.go
49+
50+
list_people_gotest: list_people.go list_people_go
51+
go test list_people.go list_people_test.go
52+
53+
javac_middleman: AddPerson.java ListPeople.java protoc_middleman
54+
javac AddPerson.java ListPeople.java com/example/tutorial/AddressBookProtos.java
55+
@touch javac_middleman
56+
57+
add_person_java: javac_middleman
58+
@echo "Writing shortcut script add_person_java..."
59+
@echo '#! /bin/sh' > add_person_java
60+
@echo 'java -classpath .:$$CLASSPATH AddPerson "$$@"' >> add_person_java
61+
@chmod +x add_person_java
62+
63+
list_people_java: javac_middleman
64+
@echo "Writing shortcut script list_people_java..."
65+
@echo '#! /bin/sh' > list_people_java
66+
@echo 'java -classpath .:$$CLASSPATH ListPeople "$$@"' >> list_people_java
67+
@chmod +x list_people_java
68+
69+
add_person_python: add_person.py protoc_middleman
70+
@echo "Writing shortcut script add_person_python..."
71+
@echo '#! /bin/sh' > add_person_python
72+
@echo './add_person.py "$$@"' >> add_person_python
73+
@chmod +x add_person_python
74+
75+
list_people_python: list_people.py protoc_middleman
76+
@echo "Writing shortcut script list_people_python..."
77+
@echo '#! /bin/sh' > list_people_python
78+
@echo './list_people.py "$$@"' >> list_people_python
79+
@chmod +x list_people_python
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
This directory contains example code that uses Protocol Buffers to manage an
2+
address book. Two programs are provided, each with three different
3+
implementations, one written in each of C++, Java, and Python. The add_person
4+
example adds a new person to an address book, prompting the user to input
5+
the person's information. The list_people example lists people already in the
6+
address book. The examples use the exact same format in all three languages,
7+
so you can, for example, use add_person_java to create an address book and then
8+
use list_people_python to read it.
9+
10+
You must install the protobuf package before you can build these.
11+
12+
To build all the examples (on a unix-like system), simply run "make". This
13+
creates the following executable files in the current directory:
14+
add_person_cpp list_people_cpp
15+
add_person_java list_people_java
16+
add_person_python list_people_python
17+
18+
If you only want to compile examples in one language, use "make cpp"*,
19+
"make java", or "make python".
20+
21+
All of these programs simply take an address book file as their parameter.
22+
The add_person programs will create the file if it doesn't already exist.
23+
24+
These examples are part of the Protocol Buffers tutorial, located at:
25+
https://developers.google.com/protocol-buffers/docs/tutorials
26+
27+
* Note that on some platforms you may have to edit the Makefile and remove
28+
"-lpthread" from the linker commands (perhaps replacing it with something else).
29+
We didn't do this automatically because we wanted to keep the example simple.
30+
31+
## Go ##
32+
33+
The Go example requires a plugin to the protocol buffer compiler, so it is not
34+
build with all the other examples. See:
35+
https://github.com/golang/protobuf
36+
for more information about Go protocol buffer support.
37+
38+
First, install the Protocol Buffers compiler (protoc).
39+
Then, install the Go Protocol Buffers plugin
40+
($GOPATH/bin must be in your $PATH for protoc to find it):
41+
go get github.com/golang/protobuf/protoc-gen-go
42+
43+
Build the Go samples in this directory with "make go". This creates the
44+
following executable files in the current directory:
45+
add_person_go list_people_go
46+
To run the example:
47+
./add_person_go addressbook.data
48+
to add a person to the protocol buffer encoded file addressbook.data. The file
49+
is created if it does not exist. To view the data, run:
50+
./list_people_go addressbook.data
51+
52+
Observe that the C++, Python, and Java examples in this directory run in a
53+
similar way and can view/modify files created by the Go example and vice
54+
versa.

0 commit comments

Comments
 (0)