Click on the asynchronous book, the top public account

Every day to share with you IT good books technology dry goods workplace knowledge

GRPC profile

GRPC (https://grpc.io) is a high-performance, open source, cross-programming language and common remote Procedure Call Protocol (RPC) framework developed by Google for communication between client and server. Using HTTP / 2 protocol and the ProtoBuf (https://developers.google.com/protocol-buffers) as a serialization tool.

GRPC mode

GRPC mainly has four request/response modes, which are as follows:

(1) Simple RPC

This mode is the most traditional, that is, the client initiates a request and the server responds to a data, which is not very different from the familiar RPC, so it will not be introduced in detail.

(2) Server-side Streaming RPC

In this mode, the client initiates a request and the server returns a continuous stream of data. A typical example is when a client sends a stock symbol to a server, and the server sends real-time data about the stock back to the client.

(3) Client-side Streaming RPC

In contrast to the server-side data flow pattern, this time the client sends a continuous stream of data to the server, and the server returns a response at the end of the transmission. A typical example is an Internet of Things terminal reporting data to a server.

(4) Bidirectional Streaming RPC

As the name implies, this is when both client and server can send data streams to each other. In this case, data from both sides can be sent to each other at the same time, that is, real-time interaction can be realized. The classic example is chatbots.

Two-way data flow actual combat

In gRPC Chinese document (http://doc.oschina.net/grpc?t=60133), there are the four modes of instances, but the example of bidirectional data flow is too simple, not reflect the two-way control characteristic, so this article to create a new case (use golang implementation), To demonstrate the gRPC two-way data flow interaction (how proTO is defined and how related packages are installed are described in the documentation, so this section is omitted in this article).

1. Proto definition

1syntax = “proto3”; // The syntax uses protocol buffer proto3


2// Package name: chat


3package chat;


4 / *


5 Service name: Chat,


6 There is only one RPC service named “BidStream”,


7 Input data flows in Request format and output data flows in Response format


8 * /


9service Chat {


10 rpc BidStream(stream Request) returns (stream Response) {}


11}


12// Request data Request format definition


13message Request {


14 string input = 1;


15}


16// Response data Response format definition


17message Response {


18 string output = 1;


19}


The server program server.go

1package main


2import (


3 “io”


4 “log”


5 “net”


6 “strconv”


7 “google.golang.org/grpc”


8 proto “chat” // Automatically generated proto code


9)


10// Streamer server


11type Streamer struct{}


12// BidStream implements the BidStream method defined in the ChatServer interface


13func (s *Streamer) BidStream(stream proto.Chat_BidStreamServer) error {


14 ctx := stream.Context()


15 for {


16 select {


17 case <-ctx.Done():


18 log.println (” received termination signal from client via context “)


19 return ctx.Err()


20 default:


21 // Receives the message from the client


22 Enter, err := stream.recv ()


23 if err == io.EOF {


24 log.println (” Data stream sent by client ends “)


25 return nil


26}


27 if err ! = nil {


28 log.Println(” Error receiving data :”, err)


29 return err


30}


31 // If the reception is normal, the corresponding instruction is executed according to the received string


32 Switch Input. Input {


33 Case “End the conversation “:


34 log.Println(” received ‘end conversation’ command “)


35 If err := stream.Send(&proto.Response{Output: “received end “}); err ! = nil {


36 return err


37}


38 // Terminates the two-way data stream with return nil when the end instruction is received


39 return nil


40 case “return data stream “:


41 log.println (” received ‘return data stream’ command “)


42 // Received Received the command ‘Return data stream’, return 10 consecutive data


43 for i := 0; i < 10; i++ {


44 If err := stream.Send(&proto.Response{Output: “stream #” + strconv.itoa (I)}); err ! = nil {


45 return err


46}


47}


48 default:


49 // By default, ‘Server return:’ + input information is returned


50 log.printf (“[received message]: %s”, enter. Input)


51 If err := stream.Send(&proto.Response{Output: “Server returns:” + input. Input}); err ! = nil {


52 return err


53}


54}


55}


56}


57}


58func main() {


59 log.Println(” Start server… )


60 server := grpc.NewServer()


61 // Register the ChatServer


62 proto.RegisterChatServer(server, &Streamer{})


63 address, err := net.Listen(“tcp”, “:3000”)


64 if err ! = nil {


65 panic(err)


66}


67 if err := server.Serve(address); err ! = nil {


68 panic(err)


69}


70}

Client program client.go

1package main


2import (


3 “bufio”


4 “context”


5 “io”


6 “log”


7 “os”


8 “google.golang.org/grpc”


9 proto “chat” // Automatically generated code according to the proto file


10)


11func main() {


12 // Create a connection


13 conn, err := grpc.Dial(“localhost:3000”, grpc.WithInsecure())


14 if err ! = nil {


15 log.printf (” Failed to connect: [%v] “, err)


16 return


17}


18 defer conn.Close()


19 // Declare the client


20 client := proto.NewChatClient(conn)


21 // Declare context


22 ctx := context.Background()


23 // Create a two-way data flow


24 stream, err := client.BidStream(ctx)


25 if err ! = nil {


26 log.printf (” Failed to create stream: [%v] “, err)


27}


28 // Start a Goroutine to receive commands from the command line


29 go func() {


30 log.Println(” Please enter a message…” )


31 Input := bufio.newreader (os.stdin)


32 for {


33 // Gets the string input from the command line, ending with carriage return


34 The character string is entered on the cli. The value is _ :=. ReadString(‘ ‘)


35 // Send the command to the server


36 If err := stream.Send(&proto.Request{Input: command line Input string}); err ! = nil {


37 return


38}


39}


40 }()


41 for {


42 // Receives data streams from the server


Err := stream.recv ()


44 if err == io.EOF {


45 log.Println(“⚠️ Receives end signal from server “)


46 break // If the end signal is received, the system exits the Receiving loop and ends the client program


47}


48 if err ! = nil {


49 // TODO: Handle receive errors


Println(” Error receiving data :”, err)


51}


52 // Prints messages from the server without errors


53 log.printf (“[client received]: %s”, response. Output)


54}


55}​

Running effect

Start the server program server.go and then the client program client.go

Enter a message that looks like the following:

conclusion

GRPC is a very powerful RPC framework, and support multi-language programming, the above server, client procedures we can completely use different languages, such as JAVA server, client with Python…

The four interaction modes of gRPC also give us a lot of room to play with, and the recent announcement of SUPPORT for gRPC by Nginx may also indicate a trend…

Asynchronous community is a material, stock, and professional IT professional book community, here you can read the latest and hottest IT books! I want to community “Git master road” this book, this book is the network programming classic books, please help me like!

This article is excerpted from the Asynchronous community, author: A Li Buge works: “gRPC Two-way Data Flow Interactive Control (GO Language Implementation)”

Recommended reading

May 2018 Book List (bonus at the end)

A list of new books for April 2018

Asynchronous books the most complete Python book list

A list of essential algorithms books for programmers

The first Python neural network programming book

Long press the QR code, you can follow us yo

I share IT articles with you every day.


In the “asynchronous books” background reply “attention”, you can get free

2,000 online video courses; Recommend friends to follow the prompts to get the free book link,
Get a free asynchronous E – edition book. Come and join us!

Click here to read more

Read the original