6

Connecting Android Apps with Server using gRPC

 1 year ago
source link: https://proandroiddev.com/connecting-android-apps-with-server-using-grpc-919719bd9a97
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Connecting Android Apps with Server using gRPC

1*1robse6VCZ33CGTnCiKrvQ.png

grpc-image

gRPC is a modern open-source high-performance Remote Procedure Call (RPC) framework that can run in any environment. It can efficiently connect services in and across data centers with pluggable support for load balancing, tracing, health checking, and authentication. It Automatically generates idiomatic client and server stubs for your service in a variety of languages and platforms. It supports Bidirectional streaming between the client and server with HTTP/2-based transport.

A RPC is a form of Client-Server Communication that uses a function call rather than a usual HTTP call.

gRPC uses ProtocolBuffers which is google’s mechanism of serializing structured data.

Protocol Buffers:

Protocol buffers provide a language-neutral, platform-neutral, extensible mechanism for serializing structured data in a forward-compatible and backward-compatible way. It’s like JSON, except it’s smaller and faster, and it generates native language bindings.

You have to create a file with an extension proto

Protocol buffers are the most commonly-used data format used by gRPC.

message Person {
string name = 1;
int32 id = 2;
}

You can consider the message as an object.

To create gRPC services.

follow this:

// The greeter service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}

gRPC uses protoc with a special gRPC plugin to generate code from your proto file: you get generated gRPC client and server code, as well as the regular protocol buffer code for populating, serializing, and retrieving your message types.

gRPC provides four kinds of services.

  1. Unary RPCs where the client sends a single request to the server and gets a single response back, just like a normal function call.
  2. Server streaming RPCs where the client sends a request to the server and gets a stream to read a sequence of messages back. The client reads from the returned stream until there are no more messages. gRPC guarantees message ordering within an individual RPC call.
  3. Client streaming RPCs where the client writes a sequence of messages and sends them to the server, again using a provided stream. Once the client has finished writing the messages, it waits for the server to read them and return its response. Again gRPC guarantees message ordering within an individual RPC call.
  4. Bidirectional streaming RPCs where both sides send a sequence of messages using a read-write stream.

Let’s connect the gRPC server with our Android App.

checkout my app code here.

checkout my gRPC server here

Step 1: Create a new android project.

1*_joIVOBn9pJd2fjd7ZBm0g.png

Step 2:

Add this in project level Gradle file’s build

buildscript {
...
dependencies {
classpath "com.google.protobuf:protobuf-gradle-plugin:0.8.18"
}
}

Now, go to app level gradle file.

Add this in plugins block

id 'com.google.protobuf'

Above dependencies block add this.

protobuf {
protoc { artifact = 'com.google.protobuf:protoc:3.19.2' }
plugins {
grpc { artifact = 'io.grpc:protoc-gen-grpc-java:1.47.0'
}
}
generateProtoTasks {
all().each { task ->
task.builtins {
java { option 'lite' }
}
task.plugins {
grpc {
option 'lite' }
}
}
}
}

Now, in the dependencies block

//grpc dependency
implementation 'io.grpc:grpc-okhttp:1.47.0'
implementation 'io.grpc:grpc-protobuf-lite:1.47.0'
implementation 'io.grpc:grpc-stub:1.47.0'
implementation 'org.apache.tomcat:annotations-api:6.0.53'

click Sync Now

Step 3:

Now, you need to create a Proto file.

root -> app -> src -> main -> proto (create this folder)

Add this file greeter.proto

Now rebuild the project. you will find a few generated files.

these are the client stubs using which we will connect to grpc server.

Step 4:

Before, exchanging data between client and server. we need to create a channel that is basically connecting the client and server.

channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext().build()

we will later provide host address and port number.

Now, to send a simple unary call.

Here,

we are using generated stub GreeterGrpcStub

and creating a HelloRequest which is our input.

and fetching the reply.

before calling this method we need to set up our local server.

Step 5:

You need Node.js.

So download from here and setup

Now, create a folder grpc-server

and run npm init -y

you need to override package.json file with this.

Now, run npm install

Now, put the same greeter.proto here in this folder.

and now create an index.js file

and put this code

Now, run node index.js

Your localhost is up and running

Step 6:

Go to MainActivity.kt

In the MainViewModel.kt

put this method

and in grpc.kt

Now, run the app.

In the field, Server add 10.0.2.2 and Port 50051

and click the Start button and click Simple RPC button. you will get a response from your local server.

1*dy9PP-fdMshOM0SSKcCj-A.png

So, you will get a reply from Server as per your code.

Now, for server streaming.

in MainViewModel.kt put this code.

fun sendMessageWithReplies(message: String) {
viewModelScope.launch(Dispatchers.IO) {
try {
updateResult(sendMessageWithReplies(message,channel).toString())
} catch (e: Exception) {
updateResult(e.message?:"")
}
}
}

and in grpc.kt

fun sendMessageWithReplies(
message: String,
channel: ManagedChannel?
):Any? {
return try {
val stub = GreeterGrpc.newBlockingStub(channel)
val request = HelloRequest.newBuilder().setName(message).build()
val reply = stub.lotsOfReplies(request)
reply.asSequence().toList().map { it -> it.message+"\n" }
} catch (e: Exception) {
e
}
}

you will receive an iterator.

1*ezb1dLai0IG9EHHT2STiaw.png

Click on Server Streaming Button and you will get a stream of messages.

Now, for Client Streaming

You need to create an asynchronous stub.

You need to create 2 stream observers one for response and request.

I have created a countdown latch to wait on the current thread.

1*JdJsQBmKKABsrqTMLaFhRQ.png

So, click on Client Streaming and you will get the output.

The same way you have to do for Bi-directional Streaming

1*NIJJfsM2xDUACLWddfMsXA.png

Click on the Bi-directional button.

That’s it.

Now, I will explain a few methods used in the Node.js server.

Here in the main() method, we are starting a grpc server at IP 0.0.0.0 and port 50051.

and adding Greeter service.

I have added some logic in different RPC calls for demonstration purposes.

for streaming requests like in the case of client streaming and bidirectional streaming. we need to have callbacks such as call.on(‘data’,null) and call.on(‘end’,null).

In the case of getting requests from stream, call object implements Readable.

In the case of sending a response on a stream, call object implements Writable.

gRPC is a very high-performing way to communicate with servers.

explore more about it here

Thank You for Reading


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK