Example usage for java.net Socket setKeepAlive

List of usage examples for java.net Socket setKeepAlive

Introduction

In this page you can find the example usage for java.net Socket setKeepAlive.

Prototype

public void setKeepAlive(boolean on) throws SocketException 

Source Link

Document

Enable/disable SocketOptions#SO_KEEPALIVE SO_KEEPALIVE .

Usage

From source file:com.googlecode.jmxtrans.connections.SocketFactory.java

/**
 * Creates the socket and the writer to go with it.
 *///  ww w .j a  v  a  2  s  .co m
@Override
public Socket makeObject(InetSocketAddress address) throws Exception {
    Socket socket = new Socket(address.getHostName(), address.getPort());
    socket.setKeepAlive(true);
    return socket;
}

From source file:net.sheehantech.cherry.pool.KeyedPooledPushSocketFactory.java

@Override
public PooledPushSocket create(K k) throws Exception {
    Socket socket = socketFactories.get(k).createSocket(gateways.get(k), ports.get(k));
    socket.setKeepAlive(true);
    PooledPushSocket pushSocket = new PooledPushSocket(socket);
    pushSocket.prepare();//w w  w. j  a va  2 s  .c o  m
    logger.info("Initialised new socket {}", pushSocket);
    return pushSocket;
}

From source file:org.lockss.util.urlconn.LockssDefaultProtocolSocketFactory.java

/**
 * This is the only factory method that handles params, thus the only one
 * we need to override./*from   w  w w . ja v  a  2 s.c o  m*/
 * @param host the host name/IP
 * @param port the port on the host
 * @param localAddress the local host name/IP to bind the socket to
 * @param localPort the local port to bing the socket to
 * @param params {@link HttpConnectionParams Http connection parameters}
 * 
 * @return Socket a new socket
 * 
 * @throws IOException if an I/O error occurs while creating the socket
 * @throws UnknownHostException if the IP address of the host cannot be
 * determined
 * @throws ConnectTimeoutException if socket cannot be connected within
 * the given time limit
 */
public Socket createSocket(final String host, final int port, final InetAddress localAddress,
        final int localPort, final HttpConnectionParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }
    Socket sock = new Socket();
    sock.bind(new InetSocketAddress(localAddress, localPort));
    sock.setKeepAlive(params.getBooleanParameter(HttpClientUrlConnection.SO_KEEPALIVE, false));
    int timeout = params.getConnectionTimeout();
    if (timeout == 0) {
        sock.connect(new InetSocketAddress(host, port));
    } else {
        try {
            sock.connect(new InetSocketAddress(host, port), timeout);
        } catch (SocketTimeoutException e) {
            // Reproduce httpclient behavior - distinguish connect timeout from
            // data timeout
            String msg = "The host did not accept the connection within timeout of " + timeout + " ms";
            throw new ConnectTimeoutException(msg, e);
        }
    }
    return sock;
}

From source file:com.tasktop.c2c.server.web.proxy.ajp.AjpPoolableConnectionFactory.java

@Override
public Object makeObject(Object objectKey) throws Exception {
    Key key = (Key) objectKey;
    String host = key.getHost();/*from   w w  w. j a  v a 2s.  com*/
    int port = key.getPort();
    if (port <= 0) {
        port = 8009;
    }

    Socket socket = socketFactory.createSocket(host, port);
    try {
        socket.setTcpNoDelay(tcpNoDelay);
        socket.setSoTimeout(soTimeout);
        socket.setKeepAlive(keepAlive);
    } catch (SocketException e) {
        socket.close();
        throw e;
    }
    debug("Created new socket: " + socket.toString());
    return socket;
}

From source file:org.apache.hadoop.dfs.TestBlockReplacement.java

private boolean replaceBlock(Block block, DatanodeInfo source, DatanodeInfo sourceProxy,
        DatanodeInfo destination) throws IOException {
    Socket sock = new Socket();
    sock.connect(NetUtils.createSocketAddr(sourceProxy.getName()), FSConstants.READ_TIMEOUT);
    sock.setKeepAlive(true);
    // sendRequest
    DataOutputStream out = new DataOutputStream(sock.getOutputStream());
    out.writeShort(FSConstants.DATA_TRANSFER_VERSION);
    out.writeByte(FSConstants.OP_COPY_BLOCK);
    out.writeLong(block.getBlockId());/*  w w w .j  av  a2s  . com*/
    out.writeLong(block.getGenerationStamp());
    Text.writeString(out, source.getStorageID());
    destination.write(out);
    out.flush();
    // receiveResponse
    DataInputStream reply = new DataInputStream(sock.getInputStream());

    short status = reply.readShort();
    if (status == FSConstants.OP_STATUS_SUCCESS) {
        return true;
    }
    return false;
}

From source file:org.apache.hadoop.hdfs.server.datanode.TestBlockReplacement.java

private boolean replaceBlock(Block block, DatanodeInfo source, DatanodeInfo sourceProxy,
        DatanodeInfo destination) throws IOException {
    Socket sock = new Socket();
    sock.connect(NetUtils.createSocketAddr(destination.getName()), HdfsConstants.READ_TIMEOUT);
    sock.setKeepAlive(true);
    // sendRequest
    DataOutputStream out = new DataOutputStream(sock.getOutputStream());
    out.writeShort(DataTransferProtocol.DATA_TRANSFER_VERSION);
    out.writeByte(DataTransferProtocol.OP_REPLACE_BLOCK);
    out.writeLong(block.getBlockId());//www.  j a  v a 2 s.  c  om
    out.writeLong(block.getGenerationStamp());
    Text.writeString(out, source.getStorageID());
    sourceProxy.write(out);
    BlockTokenSecretManager.DUMMY_TOKEN.write(out);
    out.flush();
    // receiveResponse
    DataInputStream reply = new DataInputStream(sock.getInputStream());

    short status = reply.readShort();
    if (status == DataTransferProtocol.OP_STATUS_SUCCESS) {
        return true;
    }
    return false;
}

From source file:com.newrelic.agent.deps.org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.java

@Override
public void connect(final ManagedHttpClientConnection conn, final HttpHost host,
        final InetSocketAddress localAddress, final int connectTimeout, final SocketConfig socketConfig,
        final HttpContext context) throws IOException {
    final Lookup<ConnectionSocketFactory> registry = getSocketFactoryRegistry(context);
    final ConnectionSocketFactory sf = registry.lookup(host.getSchemeName());
    if (sf == null) {
        throw new UnsupportedSchemeException(host.getSchemeName() + " protocol is not supported");
    }//  ww  w  .ja  va2 s.c  o  m
    final InetAddress[] addresses = host.getAddress() != null ? new InetAddress[] { host.getAddress() }
            : this.dnsResolver.resolve(host.getHostName());
    final int port = this.schemePortResolver.resolve(host);
    for (int i = 0; i < addresses.length; i++) {
        final InetAddress address = addresses[i];
        final boolean last = i == addresses.length - 1;

        Socket sock = sf.createSocket(context);
        sock.setSoTimeout(socketConfig.getSoTimeout());
        sock.setReuseAddress(socketConfig.isSoReuseAddress());
        sock.setTcpNoDelay(socketConfig.isTcpNoDelay());
        sock.setKeepAlive(socketConfig.isSoKeepAlive());
        final int linger = socketConfig.getSoLinger();
        if (linger >= 0) {
            sock.setSoLinger(true, linger);
        }
        conn.bind(sock);

        final InetSocketAddress remoteAddress = new InetSocketAddress(address, port);
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connecting to " + remoteAddress);
        }
        try {
            sock = sf.connectSocket(connectTimeout, sock, host, remoteAddress, localAddress, context);
            conn.bind(sock);
            if (this.log.isDebugEnabled()) {
                this.log.debug("Connection established " + conn);
            }
            return;
        } catch (final SocketTimeoutException ex) {
            if (last) {
                throw new ConnectTimeoutException(ex, host, addresses);
            }
        } catch (final ConnectException ex) {
            if (last) {
                final String msg = ex.getMessage();
                if ("Connection timed out".equals(msg)) {
                    throw new ConnectTimeoutException(ex, host, addresses);
                } else {
                    throw new HttpHostConnectException(ex, host, addresses);
                }
            }
        } catch (final NoRouteToHostException ex) {
            if (last) {
                throw ex;
            }
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connect to " + remoteAddress + " timed out. "
                    + "Connection will be retried using another IP address");
        }
    }
}

From source file:org.rifidi.emulator.io.comm.ip.tcpserver.TCPServerCommunicationIncomingConnectionHandler.java

/**
 * The main logic of this monitor, which creates a new server socket bound
 * to the current local IP / port combination and listens for clients to
 * connect until explictly unbound.//from w ww .  ja  v  a2  s  .co m
 * 
 * @see java.lang.Runnable#run()
 */
public void run() {
    logger.debug("Attempting to create TCPServer...");

    /* Create the ServerSocket and check to see 
     * if the server socket was made successfully */

    hasNoError = bindServerSocket();

    if (hasNoError) {
        logger.debug("No error creating server, proceeding.");

        /* A string which will be used multiple times in log statements. */
        String serverString = "[" + curServerSocket.getInetAddress().getHostAddress() + ":"
                + curServerSocket.getLocalPort() + "]";

        /* Keep running while the server socket is open. */
        while (!curServerSocket.isClosed() && hasNoError) {

            /* Try to accept a connection */
            Socket curClientSocket = null;
            try {
                logger.debug(serverString + " - Waiting for client...");
                curClientSocket = curServerSocket.accept();
                curClientSocket.setKeepAlive(true);
                //TODO Maybe we should do a disconnect 
            } catch (IOException e) {
                logger.debug(serverString + " - Server accept interrupted.");
                // Retry, because no Socket was created
                continue;
            }
            /* set the new Socket */
            this.hostCommunication.setClientSocket(curClientSocket);

            /* Check to see if a client successfully connected */
            if (curClientSocket != null) {
                final String connectionMessage = serverString + " - Client connected ("
                        + curClientSocket.getInetAddress().getHostAddress() + ":" + curClientSocket.getPort()
                        + ")";

                /* Log the connection */
                logger.info(connectionMessage);

                /* Call connect on the current communication. */
                this.hostCommunication.connect();

                /* Wait until the client socket is disconnected */
                synchronized (curClientSocket) {
                    while (!curClientSocket.isClosed() && curClientSocket.isConnected()) {
                        try {
                            /* Close the ServerSocket so that he couldn't accept 
                             * more than one connections a time (SYN/SYN ACK - Problem)
                             */
                            curServerSocket.close();
                            /* wait until the client connection is closed */
                            curClientSocket.wait();
                            /* bind the ServerSocket again, so that 
                             * new Connections can be made
                             */
                            PowerState powerState = this.hostCommunication.getPowerState();
                            logger.debug("Comm power state is " + powerState);
                            if (powerState != TCPServerOffCommunicationPowerState.getInstance()) {
                                hasNoError = bindServerSocket();
                            }
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (InterruptedException e) {
                            logger.debug("Interrupted Exception happened.");
                        }
                    }

                    /* Done waiting */

                }

            }

        } /* while (!serverSocket.isClosed())... */

        /* Server socket closed */

    } else {
        /* Log the error message. */
        logger.error(errorMessage);
        /* Force a shutdown of the component. */
        this.hostCommunication.turnOff();
    }
    /* All done running. */
}

From source file:org.parosproxy.paros.core.proxy.WebSocketsConnectionIntegrationTest.java

/**
 * Sends a Hello message into the channel and asserts that
 * the same message is returned by the Echo-Server.
 * The outgoing message is masked, while the incoming
 * contains the message in cleartext.//  w  w w. j  a  v a 2 s  . com
 *
 * @param socket
 * @throws IOException
 */
private void assertWorkingWebSocket(Socket socket) throws IOException {
    assertTrue("Retrieved SocketChannel should not be null.", socket != null);
    socket.setSoTimeout(500);
    socket.setTcpNoDelay(true);
    socket.setKeepAlive(true);

    byte[] maskedHelloMessage = { (byte) 0x81, (byte) 0x85, 0x37, (byte) 0xfa, 0x21, 0x3d, 0x7f, (byte) 0x9f,
            0x4d, 0x51, 0x58 };
    byte[] unmaskedHelloMessage = { (byte) 0x81, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f };

    InputStream inpStream = new BufferedInputStream(socket.getInputStream());

    OutputStream out = socket.getOutputStream();
    out.write(maskedHelloMessage);
    out.flush();

    byte[] dst = new byte[7];
    inpStream.read(dst);

    // use Arrays class to compare two byte arrays
    // returns true if it contains the same elements in same order
    assertTrue("Awaited unmasked hello message from echo server.", Arrays.equals(unmaskedHelloMessage, dst));
}

From source file:hd3gtv.as5kpc.Serverchannel.java

private Socket connect() throws IOException {
    Socket socket = new Socket();
    socket.setKeepAlive(false);
    socket.connect(new InetSocketAddress(server, port), 4000);
    return socket;
}