@Override public void onError(Throwable e) { if(subscriberOnListener != null && context != null) { if (e instanceof SocketTimeoutException) { subscriberOnListener.onError(-1001, "网络超时,请检查您的网络状态"); } else if (e instanceof ConnectException) { subscriberOnListener.onError(-1002, "网络链接中断,请检查您的网络状态"); } else if(e instanceof ExceptionApi){ subscriberOnListener.onError(((ExceptionApi)e).getCode(), ((ExceptionApi)e).getMsg()); } else { subscriberOnListener.onError(-1003, "未知错误:" + e.getMessage()); } } else { if(disposable != null && !disposable.isDisposed()) disposable.dispose(); } }
@Override public String getErrorMessage(Throwable t) { String errorMessage = "OOPs!! Something went wrong"; Timber.d(t); if (t instanceof HttpException) { errorMessage = "Errorcode"+((HttpException) t).code()+" "+t.getLocalizedMessage(); } else if (t instanceof SocketTimeoutException) { errorMessage = "SocketTimeoutException"; } else if (t instanceof IOException) { errorMessage = "Network Gone Down"; } Throwable cause = t.getCause(); if (cause instanceof RaveException) { errorMessage = cause.getLocalizedMessage(); } return errorMessage; }
public void run() { try { while (!socket.isClosed()) { pause.get().await(); try { Socket source = socket.accept(); pause.get().await(); if (receiveBufferSize > 0) { source.setReceiveBufferSize(receiveBufferSize); } LOG.info("accepted " + source + ", receiveBufferSize:" + source.getReceiveBufferSize()); synchronized (connections) { connections.add(new Bridge(source, target)); } } catch (SocketTimeoutException expected) { } } } catch (Exception e) { LOG.debug("acceptor: finished for reason: " + e.getLocalizedMessage()); } }
@Override public void run() { try { while (!socket.isClosed()) { pause.get().await(); try { Socket source = socket.accept(); pause.get().await(); if (receiveBufferSize > 0) { source.setReceiveBufferSize(receiveBufferSize); } LOG.info("accepted " + source + ", receiveBufferSize:" + source.getReceiveBufferSize()); synchronized (connections) { connections.add(new Bridge(source, target)); } } catch (SocketTimeoutException expected) { } } } catch (Exception e) { LOG.debug("acceptor: finished for reason: " + e.getLocalizedMessage()); } }
public static List<String> getStringByWalk(SnmpAccess snmp, final String oid) throws SocketTimeoutException, SocketException, AbortedException, IOException, RepeatedOidException, SnmpResponseException { List<String> result = new ArrayList<String>(); AbstractWalkProcessor<List<String>> walker = new AbstractWalkProcessor<List<String>>(result) { private static final long serialVersionUID = 1L; public void process(VarBind varbind) { StringSnmpEntry entry = new StringSnmpEntry(oid, varbind); result.add(entry.getValue()); } }; snmp.walk(oid, walker); return walker.getResult(); }
public static void initSocket(final Socket s, final String host, final int port, final JSONObject error) throws SocketException, IOException { final SocketAddress endpoint = new InetSocketAddress(host, port); try { s.setSoTimeout(1000); s.connect(endpoint, 1000); } catch (SocketTimeoutException | ConnectException | UnknownHostException e) { error.put("class", e.getClass().getSimpleName()); error.put("message", e.getMessage()); } }
@Test public void readTimeouts() throws IOException { // This relies on the fact that MockWebServer doesn't close the // connection after a response has been sent. This causes the client to // try to read more bytes than are sent, which results in a timeout. MockResponse timeout = new MockResponse().setBody("ABC").clearHeaders().addHeader("Content-Length: 4"); server.enqueue(timeout); server.enqueue(new MockResponse().setBody("unused")); // to keep the server alive URLConnection connection = urlFactory.open(server.url("/").url()); connection.setReadTimeout(1000); InputStream in = connection.getInputStream(); assertEquals('A', in.read()); assertEquals('B', in.read()); assertEquals('C', in.read()); try { in.read(); // if Content-Length was accurate, this would return -1 immediately fail(); } catch (SocketTimeoutException expected) { } in.close(); }
public static List<SnmpEntry> getMultipleSnmpEntries(SnmpAccess snmp, final List<String> oids) throws SocketTimeoutException, SocketException, AbortedException, IOException, SnmpResponseException, NoSuchMibException { String[] oidarray = oids.toArray(new String[oids.size()]); Map<String, VarBind> gots = snmp.multiGet(oidarray); List<SnmpEntry> result = new ArrayList<SnmpEntry>(); for (Map.Entry<String, VarBind> got : gots.entrySet()) { String oid = got.getKey(); VarBind vb = got.getValue(); PDU.Generic pdu = (PDU.Generic) vb.getPdu(); if (pdu.getErrorStatus() > 0) { throw new IOException("got ErrorStatus=" + pdu.getErrorStatus()); } if (SnmpV2ResponseException.noSuchInstance == vb.getV2ResponseException()) { throw new NoSuchMibException(oid); } SnmpEntry se = new SnmpEntry(oid, vb); result.add(se); } return result; }
@Override public Response intercept(final Chain chain) throws IOException { final Request request = chain.request(); final Response response; try { // try the call response = chain.proceed(request); //noinspection IfStatementWithNegatedCondition if (response.code() != HTTP_CODE_202) { return response; } else { response.body().close(); return repeatRequest(chain, request); } } catch (final SocketTimeoutException e) { throw e; } }
@Test public void expect100ContinueTimesOutWithoutContinue() throws Exception { server.enqueue(new MockResponse() .setSocketPolicy(SocketPolicy.NO_RESPONSE)); client = client.newBuilder() .readTimeout(500, TimeUnit.MILLISECONDS) .build(); Request request = new Request.Builder() .url(server.url("/")) .header("Expect", "100-continue") .post(RequestBody.create(MediaType.parse("text/plain"), "abc")) .build(); Call call = client.newCall(request); try { call.execute(); fail(); } catch (SocketTimeoutException expected) { } RecordedRequest recordedRequest = server.takeRequest(); assertEquals("", recordedRequest.getBody().readUtf8()); }
@Test(timeout = TEST_TIMEOUT) public void requestTimeoutDisabledInRequestObject_TakesPrecedenceOverClientConfiguration() { final int socketTimeout = REQUEST_TIMEOUT; // Client configuration is set arbitrarily low so that the request will be aborted if // the client configuration is incorrectly honored over the request config httpClient = new AmazonHttpClient( new ClientConfiguration().withSocketTimeout(socketTimeout).withRequestTimeout(1).withMaxErrorRetry(0)); try { EmptyHttpRequest request = newGetRequest(); request.setOriginalRequest(new EmptyAmazonWebServiceRequest().withSdkRequestTimeout(0)); execute(httpClient, request); fail("Exception expected"); } catch (AmazonClientException e) { assertThat(e.getCause(), instanceOf(SocketTimeoutException.class)); } }
private static String getNotFoundError(CoreException ce) { IStatus status = ce.getStatus(); Throwable t = status.getException(); if(t instanceof UnknownHostException || // XXX maybe a different msg ? t instanceof SocketTimeoutException || t instanceof NoRouteToHostException || t instanceof ConnectException) { Bugzilla.LOG.log(Level.FINER, null, t); return NbBundle.getMessage(BugzillaExecutor.class, "MSG_HOST_NOT_FOUND"); // NOI18N } String msg = getMessage(ce); if(msg != null) { msg = msg.trim().toLowerCase(); if(HTTP_ERROR_NOT_FOUND.equals(msg)) { Bugzilla.LOG.log(Level.FINER, "returned error message [{0}]", msg); // NOI18N return NbBundle.getMessage(BugzillaExecutor.class, "MSG_HOST_NOT_FOUND"); // NOI18N } } return null; }
@Override public String getErrorMessage(Throwable t) { String errorMessage = "OOPs!! Something went wrong"; Timber.d(t); if (t instanceof HttpException) { switch (((HttpException) t).code()){ case 500: errorMessage = "Server Down Customize message"; break; case 400: errorMessage= "Bad Request Customize Message"; break; default: break; } } else if (t instanceof SocketTimeoutException) { errorMessage = "Slow Network Connection"; } else if (t instanceof IOException) { errorMessage = "Network Gone Down"; } Throwable cause = t.getCause(); if (cause instanceof RaveException) { errorMessage = "OOPs!! Something went wrong"; } return errorMessage; }
@Override public String getErrorMessage(Throwable t) { String errorMessage = "OOPs!! Something went wrong"; Timber.d(t); if (t instanceof HttpException) { errorMessage = "Errorcode"+((HttpException) t).code()+" "+t.getLocalizedMessage(); } else if (t instanceof SocketTimeoutException) { errorMessage = "Internet Problem"; } else if (t instanceof IOException) { errorMessage = "Internet Problem"; } Throwable cause = t.getCause(); if (cause instanceof RaveException) { errorMessage = "Server Bug: "+cause.getLocalizedMessage(); } return errorMessage; }
@Test public void testRetrySocket() throws Exception { final BackgroundException failure = new BackgroundException(new SocketTimeoutException("")); SessionBackgroundAction<Void> a = new SessionBackgroundAction<Void>(new StatelessSessionPool( new TestLoginConnectionService(), new NullSession(new Host(new TestProtocol(), "t")), PathCache.empty(), new DisabledTranscriptListener(), new DefaultVaultRegistry(new DisabledPasswordCallback())), new AlertCallback() { @Override public boolean alert(final Host repeatableBackgroundAction, final BackgroundException f, final StringBuilder transcript) { assertEquals(failure, f); return false; } }, new DisabledProgressListener(), new DisabledTranscriptListener()) { @Override public Void run(final Session<?> session) throws BackgroundException { throw failure; } }; }
/** * Invocato quando un esegue un'azione * @param minBet l'importo minimo della scommessa * @param bet la scommessa * @param allowedActions la lista delle azioni consentite * @return l'azione compiuta * @throws java.io.IOException in caso di errori di stream o codifica/decodifica * @throws java.util.concurrent.TimeoutException in caso di timeout */ @Override public Action act(int minBet, int bet, Set<ActionSet> allowedActions) throws IOException, TimeoutException { out.println(JSONEncoder.getInstance().encodeAct(minBet, bet, allowedActions)); blocked = true; String toDecode = new String(); try { toDecode = in.readLine(); } catch (SocketTimeoutException ex) { throw new TimeoutException("Timeout"); } Action action = (Action)JSONDecoder.getInstance().decode(toDecode); blocked = false; return action; }
public static void handleErrors(final Throwable error, final TerminalBuffer buffer, final FileSystem fs) { Preconditions.checkNotNull(error); Preconditions.checkNotNull(buffer); Preconditions.checkNotNull(fs); if (error instanceof RenderableException) { buffer.flip(((RenderableException) error).render().render(Main.TERMINAL_WIDTH)); return; } if (error instanceof SocketTimeoutException) { final Component component = StackLayout.of( Text.of("Error! \n" + error.toString(), Color.RED), Text.of("Server did not respond in time. Are you connected to the internet?")); buffer.flip(component.render(Main.TERMINAL_WIDTH)); return; } handleUnexpectedError(error, buffer, fs); }
@Test(timeout=60000) public void testIpcConnectTimeout() throws IOException { // start server Server server = new TestServer(1, true); InetSocketAddress addr = NetUtils.getConnectAddress(server); //Intentionally do not start server to get a connection timeout // start client Client.setConnectTimeout(conf, 100); Client client = new Client(LongWritable.class, conf); // set the rpc timeout to twice the MIN_SLEEP_TIME try { call(client, new LongWritable(RANDOM.nextLong()), addr, MIN_SLEEP_TIME * 2, conf); fail("Expected an exception to have been thrown"); } catch (SocketTimeoutException e) { LOG.info("Get a SocketTimeoutException ", e); } client.stop(); }
@Override public void handleResponseError(Context context, Throwable t) { //Used to provide a monitor for handling all errors //rxjava need to use ErrorHandleSubscriber (the default implementation of Subscriber's onError method), this monitor to take effect Timber.tag("Catch-Error").w(t.getMessage()); //Here is not only print errors, but also according to different errors to make different logical processing String msg = "Unknown"; if (t instanceof UnknownHostException) { msg = "The network is not available"; } else if (t instanceof SocketTimeoutException) { msg = "Network timeout"; } else if (t instanceof HttpException) { HttpException httpException = (HttpException) t; msg = convertStatusCode(httpException); } else if (t instanceof JsonParseException || t instanceof ParseException || t instanceof JSONException || t instanceof JsonIOException) { msg = "Data parsing error"; } UiUtils.snackbarText(msg); }
protected int getErrorCode(Throwable e) { if (e instanceof RemoteAccessException) { e = e.getCause(); } if (e != null) { Class<?> cls = e.getClass(); // 是根据测试Case发现的问题,对RpcException.setCode进行设置 if (SocketTimeoutException.class.equals(cls)) { return RpcException.TIMEOUT_EXCEPTION; } else if (IOException.class.isAssignableFrom(cls)) { return RpcException.NETWORK_EXCEPTION; } else if (ClassNotFoundException.class.isAssignableFrom(cls)) { return RpcException.SERIALIZATION_EXCEPTION; } } return super.getErrorCode(e); }
/** * On the second step of two-step write, expect read timeout accessing the * redirect location, because the bogus server never sends a reply. */ @Test(timeout=TEST_TIMEOUT) public void testTwoStepWriteReadTimeout() throws Exception { startSingleTemporaryRedirectResponseThread(false); OutputStream os = null; try { os = fs.create(new Path("/file")); os.close(); // must close stream to force reading the HTTP response os = null; fail("expected timeout"); } catch (SocketTimeoutException e) { assertEquals("Read timed out", e.getMessage()); } finally { IOUtils.cleanup(LOG, os); } }
@Override public Socket connectSocket( final int connectTimeout, final Socket socket, final HttpHost host, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context ) throws IOException { Socket socket0 = socket != null ? socket : createSocket(context); if (localAddress != null) { socket0.bind(localAddress); } try { socket0.connect(remoteAddress, connectTimeout); } catch (SocketTimeoutException e) { throw new ConnectTimeoutException(e, host, remoteAddress.getAddress()); } return socket0; }
@Override public void accept(@NonNull Throwable throwable) throws Exception { throwable.printStackTrace(); if (throwable instanceof SocketTimeoutException) { if (listener != null) listener.onFialure("网络超时"); } else if (throwable instanceof JsonSyntaxException) { if (listener != null) listener.onFialure("json转换异常"); } else { if (listener != null) listener.onFialure("网络异常"); } }
private boolean isTimeout( Throwable e ) { if ( e == null ){ return( false ); } if ( e instanceof SocketTimeoutException ){ return( true ); } String message = e.getMessage(); if ( message != null ){ message = message.toLowerCase( Locale.US ); if ( message.contains( "timed out") || message.contains( "timeout" )){ return( true ); } } return( isTimeout( e.getCause())); }
public static ApiException handleException(Throwable e) { ApiException ex; if (e instanceof HttpException) { //HTTP错误 HttpException httpExc = (HttpException) e; ex = new ApiException(e, httpExc.code()); ex.setMsg("网络错误"); //均视为网络错误 return ex; } else if (e instanceof ServerException) { //服务器返回的错误 ServerException serverExc = (ServerException) e; ex = new ApiException(serverExc, serverExc.getCode()); ex.setMsg(serverExc.getMsg()); return ex; } else if (e instanceof JsonParseException || e instanceof JSONException || e instanceof ParseException || e instanceof MalformedJsonException) { //解析数据错误 ex = new ApiException(e, ANALYTIC_SERVER_DATA_ERROR); ex.setMsg("解析错误"); return ex; } else if (e instanceof ConnectException) {//连接网络错误 ex = new ApiException(e, CONNECT_ERROR); ex.setMsg("连接失败"); return ex; } else if (e instanceof SocketTimeoutException) {//网络超时 ex = new ApiException(e, TIME_OUT_ERROR); ex.setMsg("网络超时"); return ex; } else { //未知错误 ex = new ApiException(e, UN_KNOWN_ERROR); ex.setMsg("未知错误"); return ex; } }
private void handleException(final Exception x) { if (x instanceof UnknownHostException || x instanceof SocketException || x instanceof SocketTimeoutException) { // swallow log.debug("problem reading", x); } else { CrashReporter.saveBackgroundTrace(new RuntimeException(versionUrl.toString(), x), application.packageInfo()); } }
/** Test that timeout occurs when DN does not respond to RPC. * Start up a server and ask it to sleep for n seconds. Make an * RPC to the server and set rpcTimeout to less than n and ensure * that socketTimeoutException is obtained */ @Test public void testClientDNProtocolTimeout() throws IOException { final Server server = new TestServer(1, true); server.start(); final InetSocketAddress addr = NetUtils.getConnectAddress(server); DatanodeID fakeDnId = DFSTestUtil.getLocalDatanodeID(addr.getPort()); ExtendedBlock b = new ExtendedBlock("fake-pool", new Block(12345L)); LocatedBlock fakeBlock = new LocatedBlock(b, new DatanodeInfo[0]); ClientDatanodeProtocol proxy = null; try { proxy = DFSUtil.createClientDatanodeProtocolProxy( fakeDnId, conf, 500, false, fakeBlock); proxy.getReplicaVisibleLength(new ExtendedBlock("bpid", 1)); fail ("Did not get expected exception: SocketTimeoutException"); } catch (SocketTimeoutException e) { LOG.info("Got the expected Exception: SocketTimeoutException"); } finally { if (proxy != null) { RPC.stopProxy(proxy); } server.stop(); } }
private void failIfRequired() throws SocketTimeoutException { if (HUNG_READ_HOSTS.contains(this.aliasedHostname) || IMMEDIATELY_DOWNED_HOSTS.contains(this.aliasedHostname)) { sleepMillisForProperty(this.props, "socketTimeout"); throw new SocketTimeoutException(); } }
/** Returns true if this connection is ready to host new streams. */ public boolean isHealthy(boolean doExtensiveChecks) { if (socket.isClosed() || socket.isInputShutdown() || socket.isOutputShutdown()) { return false; } if (http2Connection != null) { return !http2Connection.isShutdown(); } if (doExtensiveChecks) { try { int readTimeout = socket.getSoTimeout(); try { socket.setSoTimeout(1); if (source.exhausted()) { return false; // Stream is exhausted; socket is closed. } return true; } finally { socket.setSoTimeout(readTimeout); } } catch (SocketTimeoutException ignored) { // Read timed out; socket is good. } catch (IOException e) { return false; // Couldn't read; socket is closed. } } return true; }
public static void main(String[] args) throws Exception { List<String> lines = Files.readLines(new File(LINKS_FILE_PATH), Charset.defaultCharset()); lines.stream() .filter(line -> line.startsWith("http")) .forEach(line -> { try { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(line) .get() .build(); Response response = client.newCall(request).execute(); if (response.isSuccessful()) { String respData = response.body().string(); Matcher matcher = TITLE_PATTERN.matcher(respData); if (matcher.find()) { String title = matcher.group(1); System.out.println(title + "\t:\t" + line); } } response.body().close(); } catch (Exception e) { if (e instanceof SocketTimeoutException) { System.out.println("超时: " + line); } } }); }
public void handleNamingException(NamingException e, long start, long end) { if (e.getCause() instanceof SocketTimeoutException) { // SSL connect will timeout via readReply using // SocketTimeoutException e.printStackTrace(); pass(); } else if (e.getCause() instanceof SSLHandshakeException && e.getCause().getCause() instanceof EOFException) { // test seems to be failing intermittently on some // platforms. pass(); } else { fail(e); } }
public static String getObjectId(SnmpAccess snmpAccess) throws SocketTimeoutException, SocketException, AbortedException, IOException, SnmpResponseException { VarBind objectIDVarbind = snmpAccess.getNextChild(SYS_OBJECT_ID); OidTLV objectIdOid = (OidTLV) objectIDVarbind.getValue(); return objectIdOid.getOidString(); }
@Test public void testStop() throws Exception { Tomcat tomcat = getTomcatInstance(); // No file system docBase required Context root = tomcat.addContext("", null); Wrapper w = Tomcat.addServlet(root, "tester", new TesterServlet()); w.setAsyncSupported(true); root.addServletMapping("/", "tester"); Connector connector = tomcat.getConnector(); tomcat.start(); ByteChunk bc = new ByteChunk(); int rc = getUrl("http://localhost:" + getPort() + "/", bc, null, null); assertEquals(200, rc); assertEquals("OK", bc.toString()); rc = -1; bc.recycle(); connector.stop(); try { rc = getUrl("http://localhost:" + getPort() + "/", bc, 1000, null, null); } catch (SocketTimeoutException ste) { // May also see this with NIO // Make sure the test passes if we do rc = 503; } assertEquals(503, rc); }
/** * Returns true if we are confident that we can read data from this * connection. This is more expensive and more accurate than {@link * #isAlive()}; callers should check {@link #isAlive()} first. */ public boolean isReadable() { if (!(in instanceof BufferedInputStream)) { return true; // Optimistic. } if (isSpdy()) { return true; // Optimistic. We can't test SPDY because its streams are in use. } BufferedInputStream bufferedInputStream = (BufferedInputStream) in; try { int readTimeout = socket.getSoTimeout(); try { socket.setSoTimeout(1); bufferedInputStream.mark(1); if (bufferedInputStream.read() == -1) { return false; // Stream is exhausted; socket is closed. } bufferedInputStream.reset(); return true; } finally { socket.setSoTimeout(readTimeout); } } catch (SocketTimeoutException ignored) { return true; // Read timed out; socket is good. } catch (IOException e) { return false; // Couldn't read; socket is closed. } }
/** * Handshake with the debuggee */ void handshake(Socket s, long timeout) throws IOException { s.setSoTimeout((int)timeout); byte[] hello = "JDWP-Handshake".getBytes("UTF-8"); s.getOutputStream().write(hello); byte[] b = new byte[hello.length]; int received = 0; while (received < hello.length) { int n; try { n = s.getInputStream().read(b, received, hello.length-received); } catch (SocketTimeoutException x) { throw new IOException("handshake timeout"); } if (n < 0) { s.close(); throw new IOException("handshake failed - connection prematurally closed"); } received += n; } for (int i=0; i<hello.length; i++) { if (b[i] != hello[i]) { throw new IOException("handshake failed - unrecognized message from target VM"); } } // disable read timeout s.setSoTimeout(0); }
private boolean isRecoverable(IOException e, boolean requestSendStarted) { // If there was a protocol problem, don't recover. if (e instanceof ProtocolException) { return false; } // If there was an interruption don't recover, but if there was a timeout connecting to a route // we should try the next route (if there is one). if (e instanceof InterruptedIOException) { return e instanceof SocketTimeoutException && !requestSendStarted; } // Look for known client-side or negotiation errors that are unlikely to be fixed by trying // again with a different route. if (e instanceof SSLHandshakeException) { // If the problem was a CertificateException from the X509TrustManager, // do not retry. if (e.getCause() instanceof CertificateException) { return false; } } if (e instanceof SSLPeerUnverifiedException) { // e.g. a certificate pinning error. return false; } // An example of one we might want to retry with a different route is a problem connecting to a // proxy and would manifest as a standard IOException. Unless it is one we know we should not // retry, we return true and try a new route. return true; }
public static PingResult ping(com.badlogic.gdx.net.Socket gdxSocket) throws Exception { Socket javaSocket = extractJavaSocket(gdxSocket); DataOutputStream dataOutputStream = new DataOutputStream(javaSocket.getOutputStream()); Long firstTime = System.currentTimeMillis(); dataOutputStream.writeByte(1); // 1 is ping javaSocket.setSoTimeout(TIMEOUT); try { DataInputStream dataInputStream = new DataInputStream(javaSocket.getInputStream()); PingResult pingResult = new PingResult(); pingResult.serverMajor = dataInputStream.readInt(); Long secondTime = System.currentTimeMillis(); pingResult.serverMinor = dataInputStream.readInt(); pingResult.serverPoint = dataInputStream.readInt(); pingResult.serverBuild = dataInputStream.readInt(); pingResult.serverHash = dataInputStream.readUTF(); int playerNum = dataInputStream.readInt(); pingResult.players = new String[playerNum]; for (int i = 0; i < pingResult.players.length; i++) { pingResult.players[i] = dataInputStream.readUTF(); } pingResult.ping = (int) (secondTime - firstTime); gdxSocket.dispose(); return pingResult; } catch (IOException e) { if (e instanceof SocketTimeoutException) { throw new IOException("Server did not respond in time", e); } else { throw e; } } }
@Test public void readTimeoutAppliesToHttpRequest() throws IOException { webServer.enqueue(new MockResponse() .setSocketPolicy(SocketPolicy.NO_RESPONSE)); WebSocket webSocket = newWebSocket(); clientListener.assertFailure(SocketTimeoutException.class, "timeout", "Read timed out"); assertFalse(webSocket.close(1000, null)); }
@Test public void readResponseHeaderTimeout() throws Exception { server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE)); server.enqueue(new MockResponse().setBody("A")); client = client.newBuilder() .readTimeout(1000, MILLISECONDS) .build(); // Make a call expecting a timeout reading the response headers. Call call1 = client.newCall(new Request.Builder() .url(server.url("/")) .build()); try { call1.execute(); fail("Should have timed out!"); } catch (SocketTimeoutException expected) { assertEquals("timeout", expected.getMessage()); } // Confirm that a subsequent request on the same connection is not impacted. Call call2 = client.newCall(new Request.Builder() .url(server.url("/")) .build()); Response response2 = call2.execute(); assertEquals("A", response2.body().string()); // Confirm that the connection was reused. assertEquals(0, server.takeRequest().getSequenceNumber()); assertEquals(1, server.takeRequest().getSequenceNumber()); }
/** * Test to ensure we throw a read timeout on responses that are progressing too slowly. For this * case, we take a 2KiB body and throttle it to 1KiB/second. We set the read timeout to half a * second. If our implementation is acting correctly, it will throw, as a byte doesn't arrive in * time. */ @Test public void readTimeoutOnSlowConnection() throws Exception { String body = TestUtil.repeat('y', 2048); server.enqueue(new MockResponse() .setBody(body) .throttleBody(1024, 1, SECONDS)); // Slow connection 1KiB/second. server.enqueue(new MockResponse() .setBody(body)); client = client.newBuilder() .readTimeout(500, MILLISECONDS) // Half a second to read something. .build(); // Make a call expecting a timeout reading the response body. Call call1 = client.newCall(new Request.Builder() .url(server.url("/")) .build()); Response response1 = call1.execute(); try { response1.body().string(); fail("Should have timed out!"); } catch (SocketTimeoutException expected) { assertEquals("timeout", expected.getMessage()); } // Confirm that a subsequent request on the same connection is not impacted. Call call2 = client.newCall(new Request.Builder() .url(server.url("/")) .build()); Response response2 = call2.execute(); assertEquals(body, response2.body().string()); // Confirm that the connection was reused. assertEquals(0, server.takeRequest().getSequenceNumber()); assertEquals(1, server.takeRequest().getSequenceNumber()); }