java.net.Socket.setSoTimeout()方法的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(9.3k)|赞(0)|评价(0)|浏览(243)

本文整理了Java中java.net.Socket.setSoTimeout()方法的一些代码示例,展示了Socket.setSoTimeout()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Socket.setSoTimeout()方法的具体详情如下:
包路径:java.net.Socket
类名称:Socket
方法名:setSoTimeout

Socket.setSoTimeout介绍

[英]Sets this socket's SocketOptions#SO_TIMEOUT in milliseconds. Use 0 for no timeout. To take effect, this option must be set before the blocking method was called.
[中]设置此套接字的SocketOptions#SO_超时(毫秒)。使用0表示无超时。要生效,必须在调用阻塞方法之前设置此选项。

代码示例

代码示例来源:origin: hierynomus/sshj

void onConnect() throws IOException {
  socket.setSoTimeout(timeout);
  input = socket.getInputStream();
  output = socket.getOutputStream();
}

代码示例来源:origin: alibaba/canal

public static BioSocketChannel open(SocketAddress address) throws Exception {
  Socket socket = new Socket();
  socket.setSoTimeout(BioSocketChannel.SO_TIMEOUT);
  socket.setTcpNoDelay(true);
  socket.setKeepAlive(true);
  socket.setReuseAddress(true);
  socket.connect(address, BioSocketChannel.DEFAULT_CONNECT_TIMEOUT);
  return new BioSocketChannel(socket);
}

代码示例来源:origin: oldmanpushcart/greys-anatomy

/**
 * 激活网络
 */
private Socket connect(InetSocketAddress address) throws IOException {
  final Socket socket = new Socket();
  socket.setSoTimeout(0);
  socket.connect(address, _1MIN);
  socket.setKeepAlive(true);
  socketWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
  socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  return socket;
}

代码示例来源:origin: runelite/runelite

private static int tcpPing(World world) throws IOException
  {
    try (Socket socket = new Socket())
    {
      socket.setSoTimeout(TIMEOUT);
      InetAddress inetAddress = InetAddress.getByName(world.getAddress());
      long start = System.nanoTime();
      socket.connect(new InetSocketAddress(inetAddress, PORT));
      long end = System.nanoTime();
      return (int) ((end - start) / 1000000L);
    }
  }
}

代码示例来源:origin: apache/nifi

private SocketChannel createChannel() throws IOException {
  final SocketChannel socketChannel = SocketChannel.open();
  try {
    socketChannel.configureBlocking(true);
    final Socket socket = socketChannel.socket();
    socket.setSoTimeout(timeoutMillis);
    socket.connect(new InetSocketAddress(nodeIdentifier.getLoadBalanceAddress(), nodeIdentifier.getLoadBalancePort()));
    socket.setSoTimeout(timeoutMillis);
    return socketChannel;
  } catch (final Exception e) {
    try {
      socketChannel.close();
    } catch (final Exception closeException) {
      e.addSuppressed(closeException);
    }
    throw e;
  }
}

代码示例来源:origin: NanoHttpd/nanohttpd

@Override
public void run() {
  try {
    httpd.getMyServerSocket().bind(httpd.hostname != null ? new InetSocketAddress(httpd.hostname, httpd.myPort) : new InetSocketAddress(httpd.myPort));
    hasBinded = true;
  } catch (IOException e) {
    this.bindException = e;
    return;
  }
  do {
    try {
      final Socket finalAccept = httpd.getMyServerSocket().accept();
      if (this.timeout > 0) {
        finalAccept.setSoTimeout(this.timeout);
      }
      final InputStream inputStream = finalAccept.getInputStream();
      httpd.asyncRunner.exec(httpd.createClientHandler(finalAccept, inputStream));
    } catch (IOException e) {
      NanoHTTPD.LOG.log(Level.FINE, "Communication with the client broken", e);
    }
  } while (!httpd.getMyServerSocket().isClosed());
}

代码示例来源:origin: libgdx/libgdx

public RemoteSender (String ip, int port) {
  try {
    Socket socket = new Socket(ip, port);
    socket.setTcpNoDelay(true);
    socket.setSoTimeout(3000);
    out = new DataOutputStream(socket.getOutputStream());
    out.writeBoolean(Gdx.input.isPeripheralAvailable(Peripheral.MultitouchScreen));
    connected = true;
    Gdx.input.setInputProcessor(this);
  } catch (Exception e) {
    Gdx.app.log("RemoteSender", "couldn't connect to " + ip + ":" + port);
  }
}

代码示例来源:origin: rapidoid/rapidoid

private static <T> T connectNoSSL(String address, int port, int timeout, F3<T, InputStream, BufferedReader, DataOutputStream> protocol) {
  T resp;
  try (Socket socket = new Socket(address, port)) {
    socket.setSoTimeout(timeout);
    resp = communicate(protocol, socket);
    socket.close();
  } catch (Exception e) {
    throw U.rte(e);
  }
  return resp;
}

代码示例来源:origin: apache/zookeeper

bufferedOutput = new BufferedOutputStream(sock.getOutputStream());
oa = BinaryOutputArchive.getArchive(bufferedOutput);
sock.setSoTimeout(learnerMaster.syncTimeout());
    sock.close();
  } catch(IOException ie) {

代码示例来源:origin: apache/zookeeper

s.setSoTimeout(self.tickTime * self.initLimit);
s.setTcpNoDelay(nodelay);
    s.getInputStream());
LearnerHandler fh = new LearnerHandler(s, is, Leader.this);
fh.start();
    s.close();
  } catch (IOException e) {
    LOG.warn("Error closing socket", e);

代码示例来源:origin: jenkinsci/jenkins

/**
 * Initiates the shuts down of the listener.
 */
public void shutdown() {
  shuttingDown = true;
  try {
    SocketAddress localAddress = serverSocket.getLocalAddress();
    if (localAddress instanceof InetSocketAddress) {
      InetSocketAddress address = (InetSocketAddress) localAddress;
      Socket client = new Socket(address.getHostName(), address.getPort());
      client.setSoTimeout(1000); // waking the acceptor loop should be quick
      new PingAgentProtocol().connect(client);
    }
  } catch (IOException e) {
    LOGGER.log(Level.FINE, "Failed to send Ping to wake acceptor loop", e);
  }
  try {
    serverSocket.close();
  } catch (IOException e) {
    LOGGER.log(Level.WARNING, "Failed to close down TCP port",e);
  }
}

代码示例来源:origin: apache/geode

private CommunicationMode getCommunicationModeForNonSelector(Socket socket) throws IOException {
 socket.setSoTimeout(0);
 this.socketCreator.handshakeIfSocketIsSSL(socket, this.acceptTimeout);
 byte communicationModeByte = (byte) socket.getInputStream().read();
 if (communicationModeByte == -1) {
  throw new EOFException();
 }
 return CommunicationMode.fromModeNumber(communicationModeByte);
}

代码示例来源:origin: apache/zookeeper

public static void dump(String host, int port) {
  Socket s = null;
  try {
    byte[] reqBytes = new byte[4];
    ByteBuffer req = ByteBuffer.wrap(reqBytes);
    req.putInt(ByteBuffer.wrap("dump".getBytes()).getInt());
    s = new Socket();
    s.setSoLinger(false, 10);
    s.setSoTimeout(20000);
    s.connect(new InetSocketAddress(host, port));
    InputStream is = s.getInputStream();
    OutputStream os = s.getOutputStream();
    os.write(reqBytes);
    byte[] resBytes = new byte[1024];
    int rc = is.read(resBytes);
    String retv = new String(resBytes);
    System.out.println("rc=" + rc + " retv=" + retv);
  } catch (IOException e) {
    LOG.warn("Unexpected exception", e);
  } finally {
    if (s != null) {
      try {
        s.close();
      } catch (IOException e) {
        LOG.warn("Unexpected exception", e);
      }
    }
  }
}

代码示例来源:origin: elastic/elasticsearch-hadoop

public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params)
    throws IOException, UnknownHostException, ConnectTimeoutException {
  InetSocketAddress socksAddr = new InetSocketAddress(socksHost, socksPort);
  Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksAddr);
  int timeout = params.getConnectionTimeout();
  Socket socket = new Socket(proxy);
  socket.setSoTimeout(timeout);
  SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
  SocketAddress remoteaddr = new InetSocketAddress(host, port);
  socket.bind(localaddr);
  socket.connect(remoteaddr, timeout);
  return socket;
}

代码示例来源:origin: k9mail/k-9

private void performStartTlsUpgrade(TrustedSocketFactory trustedSocketFactory,
    String host, int port, String clientCertificateAlias)
    throws MessagingException, NoSuchAlgorithmException, KeyManagementException, IOException {
  if (capabilities.stls) {
    executeSimpleCommand(STLS_COMMAND);
    socket = trustedSocketFactory.createSocket(
        socket,
        host,
        port,
        clientCertificateAlias);
    socket.setSoTimeout(RemoteStore.SOCKET_READ_TIMEOUT);
    in = new BufferedInputStream(socket.getInputStream(), 1024);
    out = new BufferedOutputStream(socket.getOutputStream(), 512);
    if (!isOpen()) {
      throw new MessagingException("Unable to connect socket");
    }
    capabilities = getCapabilities();
  } else {
    throw new CertificateValidationException(
        "STARTTLS connection security not available");
  }
}

代码示例来源:origin: stackoverflow.com

InetSocketAddress remoteAddress = new InetSocketAddress(host, port);  
SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());  
 InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);  
 sslsock.bind(isa);  
sslsock.connect(remoteAddress, connTimeout);  
sslsock.setSoTimeout(soTimeout);  
return sslsock;

代码示例来源:origin: libgdx/libgdx

public RemoteSender (String ip, int port) {
  try {
    Socket socket = new Socket(ip, port);
    socket.setTcpNoDelay(true);
    socket.setSoTimeout(3000);
    out = new DataOutputStream(socket.getOutputStream());
    out.writeBoolean(Gdx.input.isPeripheralAvailable(Peripheral.MultitouchScreen));
    connected = true;
    Gdx.input.setInputProcessor(this);
  } catch (Exception e) {
    Gdx.app.log("RemoteSender", "couldn't connect to " + ip + ":" + port);
  }
}

代码示例来源:origin: org.apache.zookeeper/zookeeper

bufferedOutput = new BufferedOutputStream(sock.getOutputStream());
oa = BinaryOutputArchive.getArchive(bufferedOutput);
sock.setSoTimeout(leader.self.tickTime * leader.self.syncLimit);
    sock.close();
  } catch(IOException ie) {

代码示例来源:origin: apache/zookeeper

private Socket createSocket() throws X509Exception, IOException {
  Socket sock;
  if (self.isSslQuorum()) {
    sock = self.getX509Util().createSSLSocket();
  } else {
    sock = new Socket();
  }
  sock.setSoTimeout(self.tickTime * self.initLimit);
  return sock;
}

代码示例来源:origin: apache/zookeeper

public void run() {
  ServerSocket ss;
  synchronized(this) {
     ss = this.ss;
  }
  while (listenerRunning) {
    try {
      Socket s = ss.accept();
      // start with the initLimit, once the ack is processed
      // in LearnerHandler switch to the syncLimit
      s.setSoTimeout(self.tickTime * self.initLimit);
      BufferedInputStream is = new BufferedInputStream(s.getInputStream());
      LearnerHandler lh = new LearnerHandler(s, is, this);
      lh.start();
    } catch (Exception e) {
      if (listenerRunning) {
        LOG.debug("Ignoring accept exception (maybe shutting down)", e);
      } else {
        LOG.debug("Ignoring accept exception (maybe client closed)", e);
      }
    }
  }
  /*
   * we don't need to close ss because we only got here because listenerRunning is
   * false and that is set and then ss is closed() in stop()
   */
}

相关文章