Created
July 23, 2021 03:04
-
-
Save amitsaha/cbc74fa75f089dee5df495c7531d16db to your computer and use it in GitHub Desktop.
Example of recreating a gRPC stream for bidi - if the client gets disconnected or there is another issue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://groups.google.com/g/grpc-io/c/PXb2Xx89QH4/m/ox_s98LOAwAJ?utm_medium=email&utm_source=footer | |
func createHelpStream(c svc.UsersClient) ( | |
users.Users_GetHelpClient, error, | |
) { | |
return c.GetHelp( | |
context.Background(), | |
grpc.WaitForReady(true), | |
) | |
} | |
func setupChat(r io.Reader, w io.Writer, c svc.UsersClient) (err error) { | |
var clientConn = make(chan svc.Users_GetHelpClient) | |
var done = make(chan bool) | |
stream, err := createHelpStream(c) | |
defer stream.CloseSend() | |
if err != nil { | |
return err | |
} | |
go func() { | |
for { | |
clientConn <- stream | |
resp, err := stream.Recv() | |
if err == io.EOF { | |
done <- true | |
} | |
if err != nil { | |
log.Printf("Recreating stream.") | |
stream, err = createHelpStream(c) | |
if err != nil { | |
close(clientConn) | |
done <- true | |
} | |
} else { | |
fmt.Printf("Response: %s\n", resp.Response) | |
time.Sleep(5 * time.Second) | |
if resp.Response == "hello-10" { | |
done <- true | |
} | |
} | |
} | |
}() | |
requestMsg := "hello" | |
msgCount := 1 | |
for { | |
if msgCount > 10 { | |
break | |
} | |
stream = <-clientConn | |
if stream == nil { | |
break | |
} | |
request := svc.UserHelpRequest{ | |
Request: fmt.Sprintf("%s-%d", requestMsg, msgCount), | |
} | |
err := stream.Send(&request) | |
if err != nil { | |
log.Printf("Send error: %v. Will retry.\n", err) | |
} else { | |
log.Printf("Request sent: %d\n", msgCount) | |
msgCount += 1 | |
} | |
} | |
<-done | |
return stream.CloseSend() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment