在Grpc-Android Java中使用双向流时如何检测(物理)断开连接

时间:2018-09-11 07:01:24

标签: java android grpc grpc-java

我使用Bidirectional Streaming使用了Grpc的{​​{1}}概念。

以下是我的代码

Async stub

现在一切正常。.我可以使用已建立的流来ping / pong服务器/客户端。但是,当我关闭服务器,并从客户端发出流请求时,它将等待无限。我除了抛出@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnOnline = (Button) findViewById(R.id.btnOnline); btnOffline = (Button) findViewById(R.id.btnOffline); btnAcceptRide = (Button) findViewById(R.id.btnAcceptRide); btnCancelRide = (Button) findViewById(R.id.btnCancelRide); txtCode = (EditText) findViewById(R.id.txtCode); txtReply = (TextView) findViewById(R.id.txtReply); ClientConnState = 0; btnOnline.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new GrpcTask().execute(); } }); private class GrpcTask extends AsyncTask<Void, Void, String> { private String mHost; private String mMessage; private int mPort; private ManagedChannel mChannel; @Override protected void onPreExecute() { mHost = "localhost"; mPort = 8080; mChannel = ManagedChannelBuilder.forAddress("192.168.0.102", 50049) .usePlaintext(true) .build(); blockingStub = bidirectionalserviceGrpc.newBlockingStub(mChannel); asyncStub = bidirectionalserviceGrpc.newStub(mChannel); } @Override protected String doInBackground(Void... nothing) { try { final CountDownLatch countDownLatch = new CountDownLatch(1); requestStreamObserver = asyncStub.requestRide(new StreamObserver<Bidirectional.RideReply>() { @Override public void onNext(Bidirectional.RideReply value) { if (countDownLatch.getCount() > 0) { countDownLatch.countDown(); } } @Override public void onError(Throwable t) { countDownLatch.countDown(); } @Override public void onCompleted() { countDownLatch.countDown(); } }); Bidirectional.RideRequest rideRequest = Bidirectional.RideRequest.newBuilder() .setRequestid(1) .setDrivercode(txtCode.getText().toString()) .build(); requestStreamObserver.onNext(rideRequest); if (!countDownLatch.await(15, TimeUnit.SECONDS)) { throw new RuntimeException( "Could not finish rpc within 1 minute, the server is likely down"); } return "completed"; } catch (Exception e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); pw.flush(); return "Failed... : " + System.lineSeparator() + sw; } } @Override protected void onPostExecute(String result) { Log.e(logger.getName(), result); } } final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { // Write Logic here super.handleMessage(msg); } }; 事件外,其他都没有。

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

根据服务器关闭的方式以及客户端的操作,TCP可能不会发现连接中断。您应该在keepAliveTime()上启用ManagedChannelBuilder。 Javadoc应该可以帮助您入门,如果您感兴趣,A8-client-side-keepalive.md将提供更多信息。

您可能还希望启用idleTimeout()