Skip to content

Instantly share code, notes, and snippets.

@bom-d-van
Last active March 26, 2023 17:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bom-d-van/1d4c16385eefb3d89d33f158c8ca77e4 to your computer and use it in GitHub Desktop.
Save bom-d-van/1d4c16385eefb3d89d33f158c8ca77e4 to your computer and use it in GitHub Desktop.

Using nc and protoc as protobuf client and server

Inspiration: Linux and Unix nc command

Example protobuf definition:

message Person {
  required string name = 1;
  required int32 id = 2;
  optional string email = 3;

  enum PhoneType {
    MOBILE = 0;
    HOME = 1;
    WORK = 2;
  }

  message PhoneNumber {
    required string number = 1;
    optional PhoneType type = 2 [default = HOME];
  }

  repeated PhoneNumber phone = 4;
}

Send a protobuf TCP request to 127.0.0.1:8080

protoc --encode=Person \
	foo.proto <<<'
		name: "John Doe"
		email: "jdoe@example.com"
		id: 43
		phone {number: "1010"}
		phone {number: "0101"}
	' \
	| nc 127.0.0.1 8080

Listening on 127.0.0.1:8080 for a TCP protobuf request

nc -l -p 8080 -c \
	| protoc --decode=Person foo.proto

Server/Client in action

sever:

protoc --encode=Person \
	foo.proto <<<'
		name: "John Doe"
		email: "jdoe@example.com"
		id: 42
	' \
	| nc -l -p 8080 -c \
	| protoc --decode=Person foo.proto

client:

protoc --encode=Person \
	foo.proto <<<'
		name: "John Doe"
		email: "jdoe@example.com"
		id: 43
		phone {number: "1010"}
	' \
	| nc 127.0.0.1 8080 \
	| protoc --decode=Person foo.proto
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment