@@ -221,6 +221,9 @@ protected void handleNotInUse() {
221221 @ Nullable
222222 final HttpConnectProxiedSocketAddress proxiedAddr ;
223223
224+ @ VisibleForTesting
225+ int proxySocketTimeout = 30000 ;
226+
224227 // The following fields should only be used for test.
225228 Runnable connectingCallback ;
226229 SettableFuture <Void > connectedFuture ;
@@ -626,8 +629,8 @@ private void sendConnectionPrefaceAndSettings() {
626629
627630 private Socket createHttpProxySocket (InetSocketAddress address , InetSocketAddress proxyAddress ,
628631 String proxyUsername , String proxyPassword ) throws StatusException {
632+ Socket sock = null ;
629633 try {
630- Socket sock ;
631634 // The proxy address may not be resolved
632635 if (proxyAddress .getAddress () != null ) {
633636 sock = socketFactory .createSocket (proxyAddress .getAddress (), proxyAddress .getPort ());
@@ -636,6 +639,9 @@ private Socket createHttpProxySocket(InetSocketAddress address, InetSocketAddres
636639 socketFactory .createSocket (proxyAddress .getHostName (), proxyAddress .getPort ());
637640 }
638641 sock .setTcpNoDelay (true );
642+ // A socket timeout is needed because lost network connectivity while reading from the proxy,
643+ // can cause reading from the socket to hang.
644+ sock .setSoTimeout (proxySocketTimeout );
639645
640646 Source source = Okio .source (sock );
641647 BufferedSink sink = Okio .buffer (Okio .sink (sock ));
@@ -682,8 +688,13 @@ private Socket createHttpProxySocket(InetSocketAddress address, InetSocketAddres
682688 statusLine .code , statusLine .message , body .readUtf8 ());
683689 throw Status .UNAVAILABLE .withDescription (message ).asException ();
684690 }
691+ // As the socket will be used for RPCs from here on, we want the socket timeout back to zero.
692+ sock .setSoTimeout (0 );
685693 return sock ;
686694 } catch (IOException e ) {
695+ if (sock != null ) {
696+ GrpcUtil .closeQuietly (sock );
697+ }
687698 throw Status .UNAVAILABLE .withDescription ("Failed trying to connect with proxy" ).withCause (e )
688699 .asException ();
689700 }
0 commit comments