Java Code Examples for java.net.Socket#setSoTimeout()
The following examples show how to use
java.net.Socket#setSoTimeout() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SocketHandler.java From smarthome with Eclipse Public License 2.0 | 6 votes |
/** * Returns a socket for the given port, (re)creates it if required. */ public Socket getSocket(int port) throws IOException { SocketInfo socketInfo = socketsPerPort.get(port); if (socketInfo == null) { logger.trace("Creating new socket for port {}", port); Socket socket = new Socket(); socket.setSoTimeout(config.getTimeout() * 1000); socket.setReuseAddress(true); socket.connect(new InetSocketAddress(config.getGatewayAddress(), port), socket.getSoTimeout()); socketInfo = new SocketInfo(socket); socketsPerPort.put(port, socketInfo); } else { boolean isMaxAliveReached = System.currentTimeMillis() - socketInfo.getCreated() > (config.getSocketMaxAlive() * 1000); if (isMaxAliveReached) { logger.debug("Max alive time reached for socket on port {}", port); removeSocket(port); return getSocket(port); } logger.trace("Returning socket for port {}", port); } return socketInfo.getSocket(); }
Example 2
Source File: CookieHttpClientTest.java From dragonwell8_jdk with GNU General Public License v2.0 | 6 votes |
@Override public void run() { Socket s = null; try { s = ss.accept(); s.setSoTimeout(TIMEOUT); readOneRequest(s.getInputStream()); s.getOutputStream().write(replyString.getBytes()); readOneRequest(s.getInputStream()); s.getOutputStream().write(replyString.getBytes()); } catch (Exception e) { e.printStackTrace(); } finally { try { if (s != null) { s.close(); } ss.close(); } catch (IOException unused) { /* gulp!burp! */ } } }
Example 3
Source File: CommonWireIOTestCase.java From netbeans with Apache License 2.0 | 6 votes |
public WireIO createWireIOClient(Socket clientSocket) { try { clientSocket.setSoTimeout(0); clientSocket.setTcpNoDelay(true); // Necessary at least on Solaris to avoid delays in e.g. readInt() etc. ObjectOutputStream socketOut = new ObjectOutputStream(clientSocket.getOutputStream()); ObjectInputStream socketIn = new ObjectInputStream(clientSocket.getInputStream()); WireIO wireIO = new WireIO(socketOut, socketIn); return wireIO; } catch (IOException ex) { ex.printStackTrace(); } return null; }
Example 4
Source File: CookieHttpClientTest.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
@Override public void run() { Socket s = null; try { s = ss.accept(); s.setSoTimeout(TIMEOUT); readOneRequest(s.getInputStream()); s.getOutputStream().write(replyString.getBytes()); readOneRequest(s.getInputStream()); s.getOutputStream().write(replyString.getBytes()); } catch (Exception e) { e.printStackTrace(); } finally { try { if (s != null) { s.close(); } ss.close(); } catch (IOException unused) { /* gulp!burp! */ } } }
Example 5
Source File: UnixConnectionSocketFactory.java From docker-client with Apache License 2.0 | 6 votes |
@Override public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context) throws IOException { if (!(socket instanceof UnixSocket)) { throw new AssertionError("Unexpected socket: " + socket); } socket.setSoTimeout(connectTimeout); try { socket.getChannel().connect(new UnixSocketAddress(socketFile)); } catch (SocketTimeoutException e) { throw new ConnectTimeoutException(e, null, remoteAddress.getAddress()); } return socket; }
Example 6
Source File: NioLaserClient.java From laser with GNU General Public License v3.0 | 6 votes |
/** * 获取并配置SocketChannel * * @return 返回SocketChannel * @throws IOException */ private SocketChannel getAndConfigSocketChannel() throws IOException { final SocketChannel socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); // config the socket final Socket socket = socketChannel.socket(); socket.setTcpNoDelay(options.isClientTcpNoDelay()); socket.setReceiveBufferSize(options.getClientSocketReceiverBufferSize()); socket.setSendBufferSize(options.getClientSocketSendBufferSize()); socket.setSoTimeout(options.getClientSocketTimeout()); socket.setPerformancePreferences( options.getClientPerformancePreferences()[0], options.getClientPerformancePreferences()[1], options.getClientPerformancePreferences()[2]); socket.setTrafficClass(options.getClientTrafficClass()); return socketChannel; }
Example 7
Source File: BlockingChannel.java From ambry with Apache License 2.0 | 6 votes |
/** * Creates and connects a Socket * @return Socket * @throws IOException */ public Socket createSocket() throws IOException { Socket tcpSocket = new Socket(); if (readBufferSize > 0) { tcpSocket.setReceiveBufferSize(readBufferSize); } if (writeBufferSize > 0) { tcpSocket.setSendBufferSize(writeBufferSize); } tcpSocket.setSoTimeout(readTimeoutMs); tcpSocket.setKeepAlive(true); tcpSocket.setTcpNoDelay(enableTcpNoDelay); tcpSocket.connect(new InetSocketAddress(host, port), connectTimeoutMs); logger.debug("Created socket with SO_TIMEOUT = {} (requested {}), " + "SO_RCVBUF = {} (requested {}), SO_SNDBUF = {} (requested {})", tcpSocket.getSoTimeout(), readTimeoutMs, tcpSocket.getReceiveBufferSize(), readBufferSize, tcpSocket.getSendBufferSize(), writeBufferSize); return tcpSocket; }
Example 8
Source File: SSLSocketTest.java From j2objc with Apache License 2.0 | 6 votes |
public void test_SSLSocket_setSoTimeout_wrapper() throws Exception { if (StandardNames.IS_RI) { // RI cannot handle this case return; } ServerSocket listening = new ServerSocket(0); // setSoTimeout applies to read, not connect, so connect first Socket underlying = new Socket(listening.getInetAddress(), listening.getLocalPort()); Socket server = listening.accept(); SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault(); Socket clientWrapping = sf.createSocket(underlying, null, -1, false); underlying.setSoTimeout(1); try { clientWrapping.getInputStream().read(); fail(); } catch (SocketTimeoutException expected) { } clientWrapping.close(); server.close(); underlying.close(); listening.close(); }
Example 9
Source File: SocketConnection.java From fastdfs-java-client with Apache License 2.0 | 5 votes |
/** * 创建与服务端连接 * * @param address 连接地址 * @param soTimeout soTimeout * @param connectTimeout 设置连接超时 */ public SocketConnection(InetSocketAddress address, int soTimeout, int connectTimeout, Charset charset) { try { socket = new Socket(); socket.setSoTimeout(soTimeout); logger.debug("开始连接到服务器 {} soTimeout={} connectTimeout={}", address, soTimeout, connectTimeout); this.charset = charset; socket.connect(address, connectTimeout); logger.debug("成功连接到服务器:{}", address); } catch (IOException e) { throw new FastDfsConnectException("不能连接到服务器:" + address, e); } }
Example 10
Source File: Connection.java From drftpd with GNU General Public License v2.0 | 5 votes |
protected void setSockOpts(Socket sock) throws IOException { /* * IPTOS_LOWCOST (0x02) IPTOS_RELIABILITY (0x04) IPTOS_THROUGHPUT (0x08) * IPTOS_LOWDELAY (0x10) */ sock.setTrafficClass(0x08); sock.setSoTimeout(TIMEOUT); }
Example 11
Source File: ApnsConnectionImpl.java From dbay-apns-for-java with Apache License 2.0 | 5 votes |
private Socket createNewSocket() throws IOException, UnknownHostException { if (logger.isDebugEnabled()) { logger.debug(connName + " create a new socket."); } isFirstWrite = true; errorHappendedLastConn = false; Socket socket = factory.createSocket(host, port); socket.setSoTimeout(readTimeOut); // enable tcp_nodelay, any data will be sent immediately. socket.setTcpNoDelay(true); return socket; }
Example 12
Source File: WebSocketClient.java From JDA with Apache License 2.0 | 5 votes |
private void prepareClose() { try { if (socket != null) { Socket rawSocket = this.socket.getSocket(); if (rawSocket != null) // attempt to set a 10 second timeout for the close frame rawSocket.setSoTimeout(10000); // this has no affect if the socket is already stuck in a read call } } catch (SocketException ignored) {} }
Example 13
Source File: TSocket.java From galaxy-sdk-java with Apache License 2.0 | 5 votes |
/** * Initializes the socket object */ private void initSocket() { socket_ = new Socket(); try { socket_.setSoLinger(false, 0); socket_.setTcpNoDelay(true); socket_.setSoTimeout(timeout_); } catch (SocketException sx) { LOGGER.error("Could not configure socket.", sx); } }
Example 14
Source File: MyHomeSocketFactory.java From openhab1-addons with Eclipse Public License 2.0 | 5 votes |
/** * Open a monitor socket with the webserver specified. * * @param ip * IP address of the webserver * @param port * of the webserver * @param passwd * of the webserver * @return the socket ready to be used * @throws IOException * if there is some problem with the socket opening */ public static Socket openMonitorSession(final String ip, final int port, final String passwd) throws IOException { Socket sk = new Socket(ip, port); sk.setSoTimeout(45 * 1000); BufferedReader inputStream = new BufferedReader(new InputStreamReader(sk.getInputStream())); PrintWriter outputStream = new PrintWriter(sk.getOutputStream(), true); String response = readUntilDelimiter(inputStream); outputStream.write(socketMonitor); outputStream.flush(); response = readUntilDelimiter(inputStream); if (!isACK(response)) { // check for passwd request String nonce = response.substring(2, response.length() - 2); String p = calcPass(passwd, nonce); outputStream.write("*#" + p + "##"); outputStream.flush(); response = readUntilDelimiter(inputStream); if (!isACK(response)) { throw new IOException("Invalid gateway password"); } } return sk; }
Example 15
Source File: ApacheThriftMethodInvoker.java From drift with Apache License 2.0 | 5 votes |
private void setSocketProperties(Socket socket) throws SocketException { socket.setSoLinger(false, 0); socket.setTcpNoDelay(true); socket.setKeepAlive(true); socket.setSoTimeout(Ints.saturatedCast(requestTimeoutMillis)); }
Example 16
Source File: TLSStreamHandler.java From Openfire with Apache License 2.0 | 4 votes |
/** * Creates a new TLSStreamHandler and secures the plain socket connection. When connecting * to a remote server then {@code clientMode} will be <code>true</code> and * {@code remoteServer} is the server name of the remote server. Otherwise {@code clientMode} * will be <code>false</code> and {@code remoteServer} null. * * @param socket the plain socket connection to secure * @param configuration the configuration for the connection * @param clientMode boolean indicating if this entity is a client or a server. * @throws java.io.IOException if an exception occurs */ public TLSStreamHandler(Socket socket, ConnectionConfiguration configuration, boolean clientMode) throws IOException { wrapper = new TLSWrapper(configuration, clientMode); tlsEngine = wrapper.getTlsEngine(); reader = new TLSStreamReader(wrapper, socket); writer = new TLSStreamWriter(wrapper, socket); // DANIELE: Add code to use directly the socket-channel. if (socket.getChannel() != null) { rbc = socket.getChannel(); wbc = socket.getChannel(); } else { rbc = Channels.newChannel(socket.getInputStream()); wbc = Channels.newChannel(socket.getOutputStream()); } initialHSStatus = HandshakeStatus.NEED_UNWRAP; initialHSComplete = false; netBBSize = tlsEngine.getSession().getPacketBufferSize(); appBBSize = tlsEngine.getSession().getApplicationBufferSize(); incomingNetBB = ByteBuffer.allocate(netBBSize); outgoingNetBB = ByteBuffer.allocate(netBBSize); outgoingNetBB.position(0); outgoingNetBB.limit(0); appBB = ByteBuffer.allocate(appBBSize); if (clientMode) { socket.setSoTimeout(0); socket.setKeepAlive(true); initialHSStatus = HandshakeStatus.NEED_WRAP; tlsEngine.beginHandshake(); } else if (configuration.getClientAuth() == Connection.ClientAuth.needed) { // Only REQUIRE client authentication if we are fully verifying certificates if (JiveGlobals.getBooleanProperty(ConnectionSettings.Server.TLS_CERTIFICATE_VERIFY, true) && JiveGlobals.getBooleanProperty(ConnectionSettings.Server.TLS_CERTIFICATE_CHAIN_VERIFY, true) && !JiveGlobals .getBooleanProperty(ConnectionSettings.Server.TLS_ACCEPT_SELFSIGNED_CERTS, false)) { tlsEngine.setNeedClientAuth(true); } else { // Just indicate that we would like to authenticate the client but if client // certificates are self-signed or have no certificate chain then we are still // good tlsEngine.setWantClientAuth(true); } } }
Example 17
Source File: BlockReconstructor.java From RDFS with Apache License 2.0 | 4 votes |
/** * Send a generated block to a datanode. * * @param datanode * Chosen datanode name in host:port form. * @param blockContents * Stream with the block contents. * @param block * Block object identifying the block to be sent. * @param blockSize * size of the block. * @param dataTransferVersion * the data transfer version * @param namespaceId * namespace id the block belongs to * @throws IOException */ private void sendReconstructedBlock(String datanode, final InputStream blockContents, DataInputStream metadataIn, Block block, long blockSize, int dataTransferVersion, int namespaceId, Progressable progress) throws IOException { InetSocketAddress target = NetUtils.createSocketAddr(datanode); Socket sock = SocketChannel.open().socket(); int readTimeout = getConf().getInt( BlockIntegrityMonitor.BLOCKFIX_READ_TIMEOUT, HdfsConstants.READ_TIMEOUT); NetUtils.connect(sock, target, readTimeout); sock.setSoTimeout(readTimeout); int writeTimeout = getConf().getInt( BlockIntegrityMonitor.BLOCKFIX_WRITE_TIMEOUT, HdfsConstants.WRITE_TIMEOUT); OutputStream baseStream = NetUtils.getOutputStream(sock, writeTimeout); DataOutputStream out = new DataOutputStream(new BufferedOutputStream( baseStream, FSConstants.SMALL_BUFFER_SIZE)); boolean corruptChecksumOk = false; boolean chunkOffsetOK = false; boolean verifyChecksum = true; boolean transferToAllowed = false; try { LOG.info("Sending block " + block + " from " + sock.getLocalSocketAddress().toString() + " to " + sock.getRemoteSocketAddress().toString()); BlockSender blockSender = new BlockSender(namespaceId, block, blockSize, 0, blockSize, corruptChecksumOk, chunkOffsetOK, verifyChecksum, transferToAllowed, metadataIn, new BlockSender.InputStreamFactory() { @Override public InputStream createStream(long offset) throws IOException { // we are passing 0 as the offset above, // so we can safely ignore // the offset passed return blockContents; } }); // Header info out.writeShort(dataTransferVersion); out.writeByte(DataTransferProtocol.OP_WRITE_BLOCK); if (dataTransferVersion >= DataTransferProtocol.FEDERATION_VERSION) { out.writeInt(namespaceId); } out.writeLong(block.getBlockId()); out.writeLong(block.getGenerationStamp()); out.writeInt(0); // no pipelining out.writeBoolean(false); // not part of recovery Text.writeString(out, ""); // client out.writeBoolean(true); // sending src node information DatanodeInfo srcNode = new DatanodeInfo(); srcNode.write(out); // Write src node DatanodeInfo // write targets out.writeInt(0); // num targets // send data & checksum blockSender.sendBlock(out, baseStream, null, progress); LOG.info("Sent block " + block + " to " + datanode); } finally { sock.close(); out.close(); } }
Example 18
Source File: ServerConnectionInitializer.java From Cubes with MIT License | 4 votes |
private static void connect(Socket javaSocket, NetJavaSocketImpl gdxSocket, DataOutputStream dataOutputStream, DataInputStream dataInputStream) throws Exception { javaSocket.setSoTimeout(0); ((ServerNetworking) Side.getNetworking()).accepted(gdxSocket); }
Example 19
Source File: Client.java From anthelion with Apache License 2.0 | 4 votes |
protected Socket __openPassiveDataConnection(int command, String arg) throws IOException, FtpExceptionCanNotHaveDataConnection { Socket socket; // // 20040317, xing, accommodate ill-behaved servers, see below // int port_previous = __passivePort; if (pasv() != FTPReply.ENTERING_PASSIVE_MODE) throw new FtpExceptionCanNotHaveDataConnection( "pasv() failed. " + getReplyString()); try { __parsePassiveModeReply(getReplyStrings()[0]); } catch (MalformedServerReplyException e) { throw new FtpExceptionCanNotHaveDataConnection(e.getMessage()); } // // 20040317, xing, accommodate ill-behaved servers, see above // int count = 0; // System.err.println("__passivePort "+__passivePort); // System.err.println("port_previous "+port_previous); // while (__passivePort == port_previous) { // // just quit if too many tries. make it an exception here? // if (count++ > 10) // return null; // // slow down further for each new try // Thread.sleep(500*count); // if (pasv() != FTPReply.ENTERING_PASSIVE_MODE) // throw new FtpExceptionCanNotHaveDataConnection( // "pasv() failed. " + getReplyString()); // //return null; // try { // __parsePassiveModeReply(getReplyStrings()[0]); // } catch (MalformedServerReplyException e) { // throw new FtpExceptionCanNotHaveDataConnection(e.getMessage()); // } // } socket = _socketFactory_.createSocket(__passiveHost, __passivePort); if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) { socket.close(); return null; } if (__remoteVerificationEnabled && !verifyRemote(socket)) { InetAddress host1, host2; host1 = socket.getInetAddress(); host2 = getRemoteAddress(); socket.close(); // our precaution throw new FtpExceptionCanNotHaveDataConnection( "Host attempting data connection " + host1.getHostAddress() + " is not same as server " + host2.getHostAddress() + " So we intentionally close it for security precaution." ); } if (__dataTimeout >= 0) socket.setSoTimeout(__dataTimeout); return socket; }
Example 20
Source File: SocketTest.java From werewolf_server with Apache License 2.0 | 4 votes |
public static void main(String[] args) throws Exception{ Socket client = new Socket("103.44.145.245", 31260); client.setSoTimeout(5000); PrintStream out = new PrintStream(client.getOutputStream()); out.print("hello"); }