Thanks for the reply. I try ServerCallStreamObserver and Context <http://www.grpc.io/grpc-java/javadoc/io/grpc/Context.html#addListener-io.grpc.Context.CancellationListener-java.util.concurrent.Executor->, and find out that they solve half of my problem: to get a callback when cancellation. Then the other half is just I was confused by myself.
So I just list all the staff here in case someone may need public StreamObserver<Message> chat(StreamObserver<Message> responseObserver){ final UserData data = new UserData(); final ServerCallStreamObserver<Message> rsob = (ServerCallStreamObserver<Message>) responseObserver; rsob.setOnCancelHandler(new Runnable() { @Override public void run() { System.out.println("OnCancelHandler:" + data.name);// } }); return new StreamObserver<Message>() { @Override public void onNext(Message value) { data.name = value.getFrom(); } UserData is a POJO. chat() will be call when client begin RPC, so just create UserData there and use it in onError and other callbacks. 在 2017年4月26日星期三 UTC+8上午12:39:51,Eric Anderson写道: > > On Tue, Apr 25, 2017 at 7:04 AM, 黄骐 <sky7...@gmail.com <javascript:>> > wrote: > >> When client make the first connect, I save the responseStreamObserver >> and link it with the client's user ID, >> so the server can use the StreamObserver when needs to push message to >> client. >> > > That sounds good. > > But now I can not find a way to identify the client when connection is >> lost and "CANNCELED" is catched in onError on server side. >> > > If the client has already completed its side of the stream, then onError > won't be called, because it can only be called once. Instead, You can call > ServerCallStreamObserver.setOnCancelHandler(Runnable) > <http://www.grpc.io/grpc-java/javadoc/io/grpc/stub/ServerCallStreamObserver.html#setOnCancelHandler-java.lang.Runnable-> > and > the Runnable will be executed if the client disconnects. To get the > ServerCallStreamObserver, simply cast the request StreamObserver. > > An alternative is to use Context.addListener(CancellationListener, > Executor) > <http://www.grpc.io/grpc-java/javadoc/io/grpc/Context.html#addListener-io.grpc.Context.CancellationListener-java.util.concurrent.Executor-> > as > the Context is also cancelled when the RPC is cancelled (all I/O failures > on server-side act like cancellation in the API). > -- You received this message because you are subscribed to the Google Groups "grpc.io" group. To unsubscribe from this group and stop receiving emails from it, send an email to grpc-io+unsubscr...@googlegroups.com. To post to this group, send email to grpc-io@googlegroups.com. Visit this group at https://groups.google.com/group/grpc-io. To view this discussion on the web visit https://groups.google.com/d/msgid/grpc-io/50fcf822-ce93-4851-a87a-3bf3c98313c1%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.