Back to Examples

gRPC service - Bidirectional streaming RPC

A grpc:Listener is created by providing the port and a grpc:Service is attached to it. In the bidirectional streaming scenario, once a client is connected to the service, the client and the service send message streams to each other. In this scenario, the two streams operate independently, and therefore, the clients and servers can read and write in any order. Use this to receive multiple request messages from a client and send multiple response messages back.

Generate the service definition

  • 1.Create a new Protocol Buffers definition file grpc_bidirectional_streaming.proto and add the service definition below.
// This is the service definition for the bidirectional streaming scenario.
syntax = "proto3";

import "google/protobuf/wrappers.proto";

service Chat {
	rpc chat (stream ChatMessage) returns (stream google.protobuf.StringValue);
}

message ChatMessage {
	string name = 1;
	string message = 2;
}
  • 2.Run the command below in the Ballerina tools distribution for stub generation.
$ bal grpc --input grpc_bidirectional_streaming.proto  --output stubs

Once you run the command, the grpc_bidirectional_streaming_pb.bal file gets generated inside the stubs directory.

Implement and run the service

  • 1.Create a Ballerina package (e.g., service). Delete the main.bal file created by default as it is not required for this example.
  • 2.Copy the generated grpc_bidirectional_streaming_pb.bal file from the stubs directory to the service package.
  • 3.Create a new grpc_bidirectional_streaming_service.bal file inside the service package and add the service implementation below.
import ballerina/grpc;
import ballerina/log;

@grpc:Descriptor {
    value: GRPC_BIDIRECTIONAL_STREAMING_DESC
}
service "Chat" on new grpc:Listener(9090) {

    // The generated code of the Ballerina gRPC command does not contain ChatStringCaller.
    // To show the usage of a caller, this RPC call uses a caller to send messages to the client.
    remote function chat(ChatStringCaller caller,
                    stream<ChatMessage, error?> clientStream) {
        // Reads and processes each message in the client stream.
        do {
            _ = check from ChatMessage chatMsg in clientStream
                do {
                    checkpanic caller->sendString(string `${chatMsg.name}: ${chatMsg.message}`);
                };
            // Once the client sends a notification to indicate the end of the stream,
            // '()' is returned by the stream.
            check caller->complete();
        } on fail error err {
            log:printError("The connection is closed with an error.", 'error = err);
        }
    }
}
  • 4.Run the service by executing the command below.
$ bal run service

Tip: You can invoke the above service via the gRPC client - Bidirectional streaming RPC.

Related links

PreviousClient-side streaming RPC
NextSend/Receive headers