Home >Backend Development >Golang >gRPC Error: How to Fix 'Connection Closed Before Server Preface Received'?

gRPC Error: How to Fix 'Connection Closed Before Server Preface Received'?

DDD
DDDOriginal
2024-12-11 07:29:09396browse

gRPC Error: How to Fix

gRPC Error: Resolving "Connection Closed Before Server Preface Received"

When attempting to connect to a gRPC server using the code snippet provided:

func newClient() *dgo.Dgraph {
    d, err := grpc.Dial("localhost:9080", grpc.WithInsecure())
    if err != nil {
        log.Fatal(err)
    }

    return dgo.NewDgraphClient(
        api.NewDgraphClient(d),
    )
}

you may encounter the following error:

rpc error: code = Unavailable desc = connection closed before server preface received

Root Cause

This error typically occurs when the server is running with Transport Layer Security (TLS) enabled, but the client is attempting to connect without using TLS.

Solution

To resolve this issue, you need to ensure that:

  1. TLS Options are Configured Correctly on the Client:

    tlsConfig := &tls.Config{
        Certificates: []tls.Certificate{myCertificate},
        RootCAs:      myCAPool,
    }
    
    tlsOpt := grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig))
    
    conn, err := grpc.DialContext(ctx, "<connection_string>", tlsOpt)
  2. Client Certificates are Used on the Client Connection:

    Make sure you are utilizing client certificates on the client connection.

By properly configuring TLS on the client, you can prevent the "connection closed before server preface received" error and establish a successful connection to the TLS-enabled server.

The above is the detailed content of gRPC Error: How to Fix 'Connection Closed Before Server Preface Received'?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn