This repository demonstrates a simple gRPC bidirectional streaming example in Go. 💻 It includes two microservices: a server that calculates the square root of numbers and a client that sends a stream of numbers to the server. 🔢
This project showcases the power of gRPC bidirectional streaming, where both the client and server can send and receive messages concurrently. 🔄 This is particularly useful for scenarios requiring continuous data exchange, real-time updates, or interactive communication. 📡
- Server: 🖥️
- Implements a gRPC server that listens on port 50051. 🎧
- Exposes a
ComputeSqrt
RPC that uses bidirectional streaming. 🔢 - Receives a stream of numbers from the client. 📥
- Calculates the square root of each number. 🧮
- Sends the square root back to the client in a stream. 📤
- Client: 💻
- Establishes a gRPC connection to the server. 🤝
- Sends a stream of numbers (from 1 to infinity) to the server every second. 📤
- Receives the stream of square roots from the server. 📥
- Prints the results to the console. 🖨️
grpc-bidirectional-streaming-demo/
├── proto/
│ └── sqrt.proto
├── server/
│ └── server.go
├── client/
│ └── client.go
└── go.mod
proto/
: Contains the Protocol Buffer definition (sqrt.proto
) for the service. 📜server/
: Contains the Go code for the gRPC server (server.go
). ⚙️client/
: Contains the Go code for the gRPC client (client.go
). 💻go.mod
: Go module definition file. 📦
- Generate gRPC code:
protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative proto/sqrt.proto
- Run the server:
go run server/server.go
- Run the client (in a separate terminal):
go run client/client.go
google.golang.org/grpc
- gRPC: A high-performance, open-source universal RPC framework. [cite: https]
- Protocol Buffers: A language-neutral mechanism for serializing structured data. [cite: https]
- Bidirectional Streaming: A gRPC communication model where both client and server can send a stream of messages concurrently. [cite: https]
Bidirectional streaming is ideal for applications that require:
- Real-time communication (e.g., chat applications, online games). [cite: https] 💬
- Continuous data streaming (e.g., sensor data, stock tickers). [cite: https] 📈
- Interactive services (e.g., remote control, collaborative editing). [cite: https] 🎮
- This example uses an insecure connection for simplicity. In a production environment, you should use secure connections with TLS. 🔒
- The client sends numbers from 1 to infinity, but you can modify this to send a finite sequence or a different range of numbers. 🔢
- The server calculates the square root of the numbers, but you can modify this to perform any other calculation or processing. 🧮