Java Code Examples for java.net.Socket.setSoTimeout()

The following are Jave code examples for showing how to use setSoTimeout() of the java.net.Socket class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: hadoop-oss   File: NuCypherExtUtilClient.java   View Source Code Vote up 7 votes
/**
 * Connect to the given datanode's datantrasfer port, and return
 * the resulting IOStreamPair. This includes encryption wrapping, etc.
 */
public static IOStreamPair connectToDN(DatanodeInfo dn, int timeout,
                                       Configuration conf,
                                       SaslDataTransferClient saslClient,
                                       SocketFactory socketFactory,
                                       boolean connectToDnViaHostname,
                                       DataEncryptionKeyFactory dekFactory,
                                       Token<BlockTokenIdentifier> blockToken)
    throws IOException {

  boolean success = false;
  Socket sock = null;
  try {
    sock = socketFactory.createSocket();
    String dnAddr = dn.getXferAddr(connectToDnViaHostname);
    LOG.debug("Connecting to datanode {}", dnAddr);
    NetUtils.connect(sock, NetUtils.createSocketAddr(dnAddr), timeout);
    sock.setSoTimeout(timeout);

    OutputStream unbufOut = NetUtils.getOutputStream(sock);
    InputStream unbufIn = NetUtils.getInputStream(sock);
    IOStreamPair pair = saslClient.newSocketSend(sock, unbufOut,
        unbufIn, dekFactory, blockToken, dn);

    IOStreamPair result = new IOStreamPair(
        new DataInputStream(pair.in),
        new DataOutputStream(new BufferedOutputStream(pair.out,
            NuCypherExtUtilClient.getSmallBufferSize(conf)))
    );

    success = true;
    return result;
  } finally {
    if (!success) {
      IOUtils.closeSocket(sock);
    }
  }
}
 
Example 2
Project: LoRaWAN-Smart-Parking   File: HttpTransport.java   View Source Code Vote up 6 votes
/**
 * Discards the response body so that the connection can be reused. This
 * needs to be done judiciously, since it delays the current request in
 * order to speed up a potential future request that may never occur.
 *
 * <p>A stream may be discarded to encourage response caching (a response
 * cannot be cached unless it is consumed completely) or to enable connection
 * reuse.
 */
private static boolean discardStream(HttpEngine httpEngine, InputStream responseBodyIn) {
  Connection connection = httpEngine.connection;
  if (connection == null) return false;
  Socket socket = connection.getSocket();
  if (socket == null) return false;
  try {
    int socketTimeout = socket.getSoTimeout();
    socket.setSoTimeout(DISCARD_STREAM_TIMEOUT_MILLIS);
    try {
      Util.skipAll(responseBodyIn);
      return true;
    } finally {
      socket.setSoTimeout(socketTimeout);
    }
  } catch (IOException e) {
    return false;
  }
}
 
Example 3
Project: FastDFS_Client   File: DefaultConnection.java   View Source Code Vote up 5 votes
/**
 * 创建与服务端连接
 * 
 * @param address
 * @param soTimeout
 * @param connectTimeout
 */
public DefaultConnection(InetSocketAddress address, int soTimeout, int connectTimeout, Charset charset) {
    try {
        socket = new Socket();
        socket.setSoTimeout(soTimeout);
        LOGGER.debug("connect to {} soTimeout={} connectTimeout={}", address, soTimeout, connectTimeout);
        this.charset = charset;
        socket.connect(address, connectTimeout);
    } catch (IOException e) {
        throw new FdfsConnectException("can't create connection to" + address, e);
    }
}
 
Example 4
Project: CrypDist   File: MessageTask.java   View Source Code Vote up 5 votes
@Override
public void run() {

    int trials = 0;
    while(trials < Config.MESSAGE_MAX_TRIALS) {

        try {
            log.debug(p.getPeerServerPort());
            log.debug(p.getAddress());
            Socket messagedClient = new Socket(p.getAddress(), p.getPeerServerPort());
            messagedClient.setSoTimeout(Config.MESSAGE_TIMEOUT);
            ObjectOutputStream out = new ObjectOutputStream(messagedClient.getOutputStream());
            out.writeInt(Config.MESSAGE_OUTGOING);
            out.writeUTF(msg);
            out.flush();

            ObjectInputStream in = new ObjectInputStream(new DataInputStream(messagedClient.getInputStream()));
            int ack = in.readInt();
            messagedClient.close();
            if (ack == Config.MESSAGE_ACK) {
                return;
            }

        } catch (IOException e) {

        }
        trials++;
    }
    log.warn("Message cannot be sent after " + Config.MESSAGE_MAX_TRIALS + " trials");
    log.warn(msg);
}
 
Example 5
Project: sether   File: ManagerRunnable.java   View Source Code Vote up 5 votes
/**
 *
 */
public void run() {
    while(true) {
        try {
            Socket connectionSocket = socket.accept();
            connectionSocket.setSoTimeout(60 * 1000); //Close after 1min to avoid socket leakage
            new ManagerThread(connectionSocket, processController).start();
        } catch(Exception e) {
            log.error("Generic error in server with message: "+e.getMessage());
        }
    }
}
 
Example 6
Project: CrypDist   File: Client.java   View Source Code Vote up 5 votes
public void initialization() {

        //Establish a connection with server, get number of active peers and their information.
        try {
            Thread t2 = new ReceiveServerRequest(this);
            t2.start();

            Socket serverConnection = new Socket(swAdr, swPort);
            serverConnection.setSoTimeout(Config.SERVER_TIMEOUT);

            DataInputStream in = new DataInputStream(serverConnection.getInputStream());

            receivePeerList(in);

            //Send itself data to server.
            DataOutputStream out = new DataOutputStream(serverConnection.getOutputStream());
            out.writeInt(heartBeatPort);
            out.writeInt(serverPort);
            out.writeUTF(Config.USER_NAME);
            out.writeUTF(Config.USER_PASS);
            out.flush();

            boolean authenticated = in.readBoolean();
            active = in.readBoolean();
            crypDist.setActive(active);
            int size = in.readInt();
            byte[] key_array = new byte[size];
            in.read(key_array);

            crypDist.setSessionKey(key_array);
            crypDist.setAuthenticated(authenticated);

            serverConnection.close();
        }
        catch(IOException e)
        {
            log.warn("Cannot connect to the server, terminated.");
            log.warn(e);
        }
    }
 
Example 7
Project: mumu   File: ClientGlobal.java   View Source Code Vote up 5 votes
/**
 * construct Socket object
 * @param ip_addr ip address or hostname
 * @param port port number
 * @return connected Socket object
 */
public static Socket getSocket(String ip_addr, int port) throws IOException {
    Socket sock = new Socket();
    sock.setSoTimeout(ClientGlobal.g_network_timeout);
    sock.connect(new InetSocketAddress(ip_addr, port), ClientGlobal.g_connect_timeout);
    return sock;
}
 
Example 8
Project: openjdk-jdk10   File: SocketTransportService.java   View Source Code Vote up 5 votes
/**
 * 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);
}
 
Example 9
Project: Cubes   File: ClientConnectionInitializer.java   View Source Code Vote up 5 votes
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;
    }
  }
}
 
Example 10
Project: vase   File: HttpUtils.java   View Source Code Vote up 5 votes
private static Socket initSocket(Config config, InetSocketAddress address) throws IOException {
    Socket socket = new Socket();
    socket.setSoTimeout(config.mTransportTimeOut);
    socket.connect(address, config.mConnectTimeOut);
    socket.setKeepAlive(true);
    return socket;
}
 
Example 11
Project: lighthouse   File: BHttpConnectionBase.java   View Source Code Vote up 5 votes
private int fillInputBuffer(final int timeout) throws IOException {
    final Socket socket = this.socketHolder.get();
    final int oldtimeout = socket.getSoTimeout();
    try {
        socket.setSoTimeout(timeout);
        return this.inbuffer.fillBuffer();
    } finally {
        socket.setSoTimeout(oldtimeout);
    }
}
 
Example 12
Project: Nird2   File: TorPlugin.java   View Source Code Vote up 5 votes
@Override
public DuplexTransportConnection createConnection(ContactId c) {
	if (!isRunning()) return null;
	TransportProperties p = callback.getRemoteProperties().get(c);
	if (p == null) return null;
	String onion = p.get(PROP_ONION);
	if (StringUtils.isNullOrEmpty(onion)) return null;
	if (!ONION.matcher(onion).matches()) {
		// not scrubbing this address, so we are able to find the problem
		if (LOG.isLoggable(INFO)) LOG.info("Invalid hostname: " + onion);
		return null;
	}
	Socket s = null;
	try {
		if (LOG.isLoggable(INFO))
			LOG.info("Connecting to " + scrubOnion(onion));
		controlConnection.forgetHiddenService(onion);
		s = torSocketFactory.createSocket(onion + ".onion", 80);
		s.setSoTimeout(socketTimeout);
		if (LOG.isLoggable(INFO))
			LOG.info("Connected to " + scrubOnion(onion));
		return new TorTransportConnection(this, s);
	} catch (IOException e) {
		if (LOG.isLoggable(INFO)) {
			LOG.info("Could not connect to " + scrubOnion(onion) + ": " +
					e.toString());
		}
		tryToClose(s);
		return null;
	}
}
 
Example 13
Project: mumu   File: ClientGlobal.java   View Source Code Vote up 5 votes
/**
 * construct Socket object
 * @param addr InetSocketAddress object, including ip address and port
 * @return connected Socket object
 */
public static Socket getSocket(InetSocketAddress addr) throws IOException {
    Socket sock = new Socket();
    sock.setSoTimeout(ClientGlobal.g_network_timeout);
    sock.connect(addr, ClientGlobal.g_connect_timeout);
    return sock;
}
 
Example 14
Project: mokka7   File: S7Client.java   View Source Code Vote up 5 votes
private void openTcpConnect(int timeout) throws S7Exception {
    try {
        tcpSocket = new Socket();
        tcpSocket.connect(new InetSocketAddress(config.getHost(), config.getPort()), timeout);
        tcpSocket.setTcpNoDelay(true);
        tcpSocket.setSoTimeout(recvTimeout);
        inStream = new BufferedInputStream(tcpSocket.getInputStream());
        outStream = new BufferedOutputStream(tcpSocket.getOutputStream());
    } catch (IOException e) {
        throw buildException(TCP_CONNECTION_FAILED, e);
    }
}
 
Example 15
Project: iBase4J   File: ServerInfo.java   View Source Code Vote up 5 votes
/**
* connect to server
* @return connected Socket object
*/
	public Socket connect() throws IOException
	{
		Socket sock = new Socket();
		sock.setReuseAddress(true);
		sock.setSoTimeout(ClientGlobal.g_network_timeout);
		sock.connect(new InetSocketAddress(this.ip_addr, this.port), ClientGlobal.g_connect_timeout);
		return sock;
	}
 
Example 16
Project: ddpush   File: Pusher.java   View Source Code Vote up 4 votes
private void initSocket()throws Exception{
	socket = new Socket(this.host, this.port);
	socket.setSoTimeout(timeout);
	in = socket.getInputStream();
	out = socket.getOutputStream();
}
 
Example 17
Project: tomcat7   File: TestCometProcessor.java   View Source Code Vote up 4 votes
@Test
public void testSyncClose() throws Exception {
    Assume.assumeTrue(
            "This test is skipped, because this connector does not support Comet.",
            isCometSupported());

    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context root = tomcat.addContext("", null);
    Tomcat.addServlet(root, "comet", new CometCloseServlet());
    root.addServletMapping("/comet", "comet");
    Tomcat.addServlet(root, "hello", new HelloWorldServlet());
    root.addServletMapping("/hello", "hello");
    tomcat.getConnector().setProperty("connectionTimeout", "5000");
    tomcat.start();

    // Create connection to Comet servlet
    final Socket socket =
        SocketFactory.getDefault().createSocket("localhost", getPort());
    socket.setSoTimeout(5000);

    final OutputStream os = socket.getOutputStream();
    String requestLine = "POST http://localhost:" + getPort() +
            "/comet HTTP/1.1\r\n";
    os.write(requestLine.getBytes());
    os.write("transfer-encoding: chunked\r\n".getBytes());
    os.write("\r\n".getBytes());
    // Don't send any data
    os.write("0\r\n\r\n".getBytes());

    InputStream is = socket.getInputStream();
    ResponseReaderThread readThread = new ResponseReaderThread(is);
    readThread.start();

    // Wait for the comet request/response to finish
    int count = 0;
    while (count < 10 && !readThread.getResponse().endsWith("0\r\n\r\n")) {
        Thread.sleep(500);
        count++;
    }

    Assert.assertTrue(readThread.getResponse().contains("2\r\nOK"));

    if (count == 10) {
        fail("Comet request did not complete");
    }

    // Send a standard HTTP request on the same connection
    requestLine = "GET http://localhost:" + getPort() +
            "/hello HTTP/1.1\r\n";
    os.write(requestLine.getBytes());
    os.write("connection: close\r\n".getBytes());
    os.write("\r\n".getBytes());

    // Check for the expected response
    count = 0;
    while (count < 10 && !readThread.getResponse().contains(
            HelloWorldServlet.RESPONSE_TEXT)) {
        Thread.sleep(500);
        count++;
    }

    if (count == 10) {
        fail("Non-comet request did not complete");
    }

    readThread.join();
    os.close();
    is.close();
}
 
Example 18
Project: Cubes_2   File: ClientConnectionInitializer.java   View Source Code Vote up 4 votes
/**
 * connect
 * 
 * @param gdxSocket
 * @throws Exception
 */
public static void connect(com.badlogic.gdx.net.Socket gdxSocket) throws Exception {
	Socket javaSocket = extractJavaSocket(gdxSocket);
	DataOutputStream dataOutputStream = new DataOutputStream(javaSocket.getOutputStream());
	dataOutputStream.writeByte(0); // 0 is connect
	javaSocket.setSoTimeout(TIMEOUT);
	int serverMajor;
	int serverMinor;
	int serverPoint;
	int serverBuild;
	String serverHash;
	try {
		DataInputStream dataInputStream = new DataInputStream(javaSocket.getInputStream());
		serverMajor = dataInputStream.readInt();
		serverMinor = dataInputStream.readInt();
		serverPoint = dataInputStream.readInt();
		serverBuild = dataInputStream.readInt();
		serverHash = dataInputStream.readUTF();
	} catch (IOException e) {
		if (e instanceof SocketTimeoutException) {
			throw new IOException("Server did not respond in time", e);
		} else {
			throw e;
		}
	}
	if (serverMajor == Branding.VERSION_MAJOR && serverMinor == Branding.VERSION_MINOR
			&& serverPoint == Branding.VERSION_POINT) {
		if (serverBuild == Branding.VERSION_BUILD) {
			if (!serverHash.equals(Branding.VERSION_HASH)) {
				Log.warning("Server reports the same build, but has a different hash");
			} else {
				Log.debug("Server is running exactly the same build");
			}
		} else {
			Log.warning("Server is running build " + serverBuild);
		}
	} else {
		String str = serverMajor + "." + serverMinor + "." + serverPoint;
		throw new IOException("Server is running version " + str + " not " + Branding.VERSION_MAJOR_MINOR_POINT);
	}
	javaSocket.setSoTimeout(0);
}
 
Example 19
Project: Cubes   File: ServerConnectionInitializer.java   View Source Code Vote up 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 20
Project: apache-tomcat-7.0.73-with-comment   File: TestCometProcessor.java   View Source Code Vote up 4 votes
@Test
public void testSyncClose() throws Exception {
    Assume.assumeTrue(
            "This test is skipped, because this connector does not support Comet.",
            isCometSupported());

    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context root = tomcat.addContext("", null);
    Tomcat.addServlet(root, "comet", new CometCloseServlet());
    root.addServletMapping("/comet", "comet");
    Tomcat.addServlet(root, "hello", new HelloWorldServlet());
    root.addServletMapping("/hello", "hello");
    tomcat.getConnector().setProperty("connectionTimeout", "5000");
    tomcat.start();

    // Create connection to Comet servlet
    final Socket socket =
        SocketFactory.getDefault().createSocket("localhost", getPort());
    socket.setSoTimeout(5000);

    final OutputStream os = socket.getOutputStream();
    String requestLine = "POST http://localhost:" + getPort() +
            "/comet HTTP/1.1\r\n";
    os.write(requestLine.getBytes());
    os.write("transfer-encoding: chunked\r\n".getBytes());
    os.write("\r\n".getBytes());
    // Don't send any data
    os.write("0\r\n\r\n".getBytes());

    InputStream is = socket.getInputStream();
    ResponseReaderThread readThread = new ResponseReaderThread(is);
    readThread.start();

    // Wait for the comet request/response to finish
    int count = 0;
    while (count < 10 && !readThread.getResponse().endsWith("0\r\n\r\n")) {
        Thread.sleep(500);
        count++;
    }

    Assert.assertTrue(readThread.getResponse().contains("2\r\nOK"));

    if (count == 10) {
        fail("Comet request did not complete");
    }

    // Send a standard HTTP request on the same connection
    requestLine = "GET http://localhost:" + getPort() +
            "/hello HTTP/1.1\r\n";
    os.write(requestLine.getBytes());
    os.write("connection: close\r\n".getBytes());
    os.write("\r\n".getBytes());

    // Check for the expected response
    count = 0;
    while (count < 10 && !readThread.getResponse().contains(
            HelloWorldServlet.RESPONSE_TEXT)) {
        Thread.sleep(500);
        count++;
    }

    if (count == 10) {
        fail("Non-comet request did not complete");
    }

    readThread.join();
    os.close();
    is.close();
}