CodeBlanks Logo Icon CodeBlanks

gRPC client

Learn to call a remote method with a gRPC client.

A gRPC client

The client opens a connection and makes calls with the generated client type. Every call gets a context with a timeout:

conn, err := grpc.NewClient("localhost:50051",
    grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil { log.Fatal(err) }
defer conn.Close()

c := pb.NewSelamlayiciClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
r, err := c.Selam(ctx, &pb.SelamIstek{Ad: "Ada"})

Share the connection

A grpc.ClientConn is expensive and safe for concurrent use; instead of opening a new connection per call, one is shared across the application. insecure.NewCredentials() is only for local development; production uses TLS credentials.

Practice Timeout

Create ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) and write defer cancel(). Wait with select on time.After(50*time.Millisecond) and ctx.Done(); if the context ends first, print ctx.Err().

Starter code

main.go
package main

import (
    "context"
    "fmt"
    "time"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "context"
    "fmt"
    "time"
)

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
    defer cancel()
    select {
    case <-time.After(50 * time.Millisecond):
        fmt.Println("yanıt geldi")
    case <-ctx.Done():
        fmt.Println(ctx.Err())
    }
}

Expected output

context deadline exceeded

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why is a context with a timeout passed to a client call?

  • To open the connection
  • To read the proto file
  • So the call doesn't wait forever if the server doesn't respond Correct answer
  • To encrypt the message

Explanation: When time runs out the call ends with codes.DeadlineExceeded; the deadline also propagates to the server, which can stop working.

2 Create the client

Question
c := pb.____(conn)
Answer
c := pb.NewSelamlayiciClient(conn)

Explanation: The generated New...Client function builds a client from the connection.

3 Client parts

Term Meaning
grpc.NewClient Connection
New...Client Generated client
context.WithTimeout Time limit
conn.Close Closes the connection

All lessons in Advanced