long now = System.currentTimeMillis(); if (selector == null) { selector = Selector.open(); key = channel.register(selector, SelectionKey.OP_READ); } else { key.interestOps(SelectionKey.OP_READ); int keyCount = selector.select(this.getSoTimeout()); if (keyCount == 0 && this.getSoTimeout() > 0 && ((System.currentTimeMillis() - now) >= this.getSoTimeout())) { throw new SocketTimeoutException("Timeout during handshake"); readable = key.isReadable(); if (key!=null) try {key.cancel();} catch (Exception ignore) {} if (selector!=null) try {selector.close();} catch (Exception ignore) {}
SocketChannel ch = socket.getChannel(); "Local address %s must be of same family as remote address %s.", localAddr, endpoint); socket.bind(localAddr); if (ch == null) { socket.connect(endpoint, timeout); } else { SocketIOWithTimeout.connect(ch, endpoint, timeout); throw new ConnectTimeoutException(ste.getMessage()); LOG.info("Detected a loopback TCP socket, disconnecting it"); socket.close(); throw new ConnectException( "Localhost targeted connection resulted in a loopback. " + "No daemon is listening on the target port.");
if (exception instanceof ConnectException) { return (ConnectException) new ConnectException( "Call to " + addr + " failed on connection exception: " + exception).initCause(exception); } else if (exception instanceof SocketTimeoutException) { return (SocketTimeoutException) new SocketTimeoutException( "Call to " + addr + " failed because " + exception).initCause(exception); } else if (exception instanceof ConnectionClosingException) { return (ConnectionClosingException) new ConnectionClosingException(
@Override protected IOException newTimeoutException(IOException cause) { SocketTimeoutException socketTimeoutException = new SocketTimeoutException("timeout"); if (cause != null) { socketTimeoutException.initCause(cause); } return socketTimeoutException; }
/** * 针对某个IP第index次connect */ private void execSocket(InetSocketAddress socketAddress, int timeOut, int index) { Socket socket = null; long start = 0; long end = 0; try { socket = new Socket(); start = System.currentTimeMillis(); socket.connect(socketAddress, timeOut); end = System.currentTimeMillis(); RttTimes[index] = end - start; } catch (SocketTimeoutException e) { RttTimes[index] = -1;// 作为TIMEOUT标识 e.printStackTrace(); } catch (IOException e) { RttTimes[index] = -2;// 作为IO异常标识 e.printStackTrace(); } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
private byte [] _recv(int length) throws IOException { SocketChannel channel = (SocketChannel) key.channel(); int nrecvd = 0; byte [] data = new byte[length]; ByteBuffer buffer = ByteBuffer.wrap(data); key.interestOps(SelectionKey.OP_READ); try { while (nrecvd < length) { if (key.isReadable()) { long n = channel.read(buffer); if (n < 0) throw new EOFException(); nrecvd += (int) n; if (nrecvd < length && System.currentTimeMillis() > endTime) throw new SocketTimeoutException(); } else blockUntil(key, endTime); } } finally { if (key.isValid()) key.interestOps(0); } return data; }
void send(byte [] data) throws IOException { SocketChannel channel = (SocketChannel) key.channel(); verboseLog("TCP write", data); byte [] lengthArray = new byte[2]; buffers[1] = ByteBuffer.wrap(data); int nsent = 0; key.interestOps(SelectionKey.OP_WRITE); try { while (nsent < data.length + 2) { if (key.isWritable()) { long n = channel.write(buffers); if (n < 0) throw new EOFException(); if (nsent < data.length + 2 && System.currentTimeMillis() > endTime) throw new SocketTimeoutException(); } else blockUntil(key, endTime);
public void listen() throws IOException { String command; while(true){ //System.out.println("Listening for commands"); try{ DataInputStream in = new DataInputStream(this.socket.getInputStream()); DataOutputStream out = new DataOutputStream(this.socket.getOutputStream()); command = receive(in); send(serve(command), out); } catch (SocketTimeoutException e) { e.printStackTrace(); } } }
@Override public boolean connect(SocketAddress remote) throws IOException { long start = System.currentTimeMillis(); //log.debug("trying to connect"); socketChannel.connect(remote); if (selector.select(connectTimeout) > 0) { selector.selectedKeys().remove(channelKey); //log.debug("selected connect"); //log.debug("Spent " + (System.currentTimeMillis() - start)); if (!channelKey.isConnectable()) { throw new IllegalStateException("Socket channel is in not connectable state"); } socketChannel.finishConnect(); channelKey = socketChannel.register(selector, SelectionKey.OP_READ); if (log.isDebugEnabled()) { log.debug("Connected socket in " + (System.currentTimeMillis() - start)); } if (!socketChannel.isConnected()) { throw new SocketException("SocketChannel not connected on some reason"); } return true; } //log.debug("Spent " + (System.currentTimeMillis() - start)); throw new SocketTimeoutException("Failed to connect to " + remote.toString()); }
logger.warn("Timing out TcpNioConnection " + connection.getConnectionId()); SocketTimeoutException exception = new SocketTimeoutException("Timing out connection"); connection.publishConnectionExceptionEvent(exception); connection.timeout(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> iterator = keys.iterator(); while (iterator.hasNext()) { iterator.remove(); try { if (!key.isValid()) { logger.debug("Selection key no longer valid"); else if (key.isReadable()) { key.interestOps(key.interestOps() - SelectionKey.OP_READ); final TcpNioConnection connection; connection = (TcpNioConnection) key.attachment(); if (key.channel().isOpen()) { key.interestOps(SelectionKey.OP_READ); selector.wakeup();
final long expires; if (origTimeout > 0) { socket.setSoTimeout(timeout); expires = System.currentTimeMillis() + timeout; } else { expires = 0; final Reader reader = new UTF8Reader(socket.getInputStream()); while ( (c = reader.read()) != -1) { if (++i > MAX_LINE_LENGTH) int newTimeout = (int) (expires - System.currentTimeMillis()); if (newTimeout <= 0) throw new SocketTimeoutException(); buf.append((char)c); if (newTimeout != timeout) { timeout = newTimeout; socket.setSoTimeout(timeout); throw new SocketTimeoutException(); else throw new EOFException();
protected synchronized void doWrite(ByteBuffer buffer) throws IOException { if (logger.isDebugEnabled()) { logger.debug(getConnectionId() + " writing " + buffer.remaining()); } TcpNioConnection.this.socketChannel.write(buffer); int remaining = buffer.remaining(); if (remaining == 0) { return; } if (this.selector == null) { this.selector = Selector.open(); this.soTimeout = TcpNioConnection.this.socketChannel.socket().getSoTimeout(); } TcpNioConnection.this.socketChannel.register(this.selector, SelectionKey.OP_WRITE); while (remaining > 0) { int selectionCount = this.selector.select(this.soTimeout); if (selectionCount == 0) { throw new SocketTimeoutException("Timeout on write"); } this.selector.selectedKeys().clear(); TcpNioConnection.this.socketChannel.write(buffer); remaining = buffer.remaining(); } }
OutputStream out = sock.getOutputStream(); throw new SocketTimeoutException("Write timed out (socket was concurrently closed).");
void send(byte [] data) throws IOException { SocketChannel channel = (SocketChannel) key.channel(); verboseLog("TCP write", channel.socket().getLocalSocketAddress(), channel.socket().getRemoteSocketAddress(), data); byte [] lengthArray = new byte[2]; lengthArray[0] = (byte)(data.length >>> 8); buffers[1] = ByteBuffer.wrap(data); int nsent = 0; key.interestOps(SelectionKey.OP_WRITE); try { while (nsent < data.length + 2) { if (key.isWritable()) { long n = channel.write(buffers); if (n < 0) throw new EOFException(); if (nsent < data.length + 2 && System.currentTimeMillis() > endTime) throw new SocketTimeoutException(); } else blockUntil(key, endTime);
sock.close(); throw new SocketTimeoutException(); log.info("IO error on message send [locNode=" + locNode + ", msg=" + msg + ']'); sock.close(); throw new SocketTimeoutException(); sock.close();
try { if (channel == null) { channel = SocketChannel.open(); channel.configureBlocking(false); channel.setOption(StandardSocketOptions.SO_SNDBUF, maxSendBufferSize); final int actualSendBufSize = channel.getOption(StandardSocketOptions.SO_SNDBUF); if (actualSendBufSize < maxSendBufferSize) { while (!channel.finishConnect()) { if (System.currentTimeMillis() > startTime + timeout) { throw new SocketTimeoutException("Timed out connecting to " + host + ":" + port);
logger.debug("Starting TLS handshake with {}. Timeout is {}ms", socketChannel.socket(), timeout); if (socketChannel.socket().isClosed()) { logger.info("Handshake terminated because socket is closed"); throw new SocketException("handshake terminated - socket is closed"); if (timeoutNanos < System.nanoTime()) { logger.info("TLS handshake is timing out"); throw new SocketTimeoutException("handshake timed out"); case NEED_UNWRAP: int dataRead = socketChannel.read(handshakeBuffer);
SocketAddress endpoint, int timeout) throws IOException { boolean blockingOn = channel.isBlocking(); if (blockingOn) { channel.configureBlocking(false); if (channel.connect(endpoint)) { return; (timeout > 0 && (timeoutLeft = (endTime - Time.now())) <= 0)) { throw new SocketTimeoutException( timeoutExceptionString(channel, timeout, SelectionKey.OP_CONNECT));
@Test public void testNotStaleWhenTimeout() throws Exception { final InputStream inStream = Mockito.mock(InputStream.class); Mockito.when(socket.getInputStream()).thenReturn(inStream); Mockito.when(inStream.read(ArgumentMatchers.<byte []>any(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt())) .thenThrow(new SocketTimeoutException()); conn.bind(socket); conn.ensureOpen(); Assert.assertFalse(conn.isStale()); }
static protected void blockUntil(SelectionKey key, long endTime) throws IOException { long timeout = endTime - System.currentTimeMillis(); int nkeys = 0; if (timeout > 0) nkeys = key.selector().select(timeout); else if (timeout == 0) nkeys = key.selector().selectNow(); if (nkeys == 0) throw new SocketTimeoutException(); }