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:org.psit.transwatcher.TransWatcher.java

@Override
public void run() {

    try {/* w w w.ja v  a  2s  .  c  o  m*/
        while (true) {

            String cardIP = connectAndGetCardIP();
            if (cardIP != null) {
                notifyMessage("Found SD card, IP: " + cardIP);

                // handshake successful, open permanent TCP connection
                // to listen to new images
                Socket newImageListenerSocket = null;
                try {
                    newImageListenerSocket = new Socket(cardIP, 5566);
                    newImageListenerSocket.setKeepAlive(true);
                    InputStream is = newImageListenerSocket.getInputStream();
                    byte[] c = new byte[1];
                    byte[] singleMessage = new byte[255];
                    int msgPointer = 0;

                    startConnectionKeepAliveWatchDog(newImageListenerSocket);

                    startImageDownloaderQueue(cardIP);

                    setState(State.LISTENING);

                    // loop to wait for new images
                    while (newImageListenerSocket.isConnected()) {
                        if (is.read(c) == 1) {
                            if (0x3E == c[0]) { // >
                                // start of filename
                                msgPointer = 0;
                            } else if (0x00 == c[0]) {
                                // end of filename
                                String msg = new String(Arrays.copyOfRange(singleMessage, 0, msgPointer));
                                notifyMessage("Image shot: " + msg);

                                // add to download queue
                                queue.add(msg);
                            } else {
                                // single byte. add to buffer
                                singleMessage[msgPointer++] = c[0];
                            }
                        }
                    }
                    setState(State.SEARCHING_CARD);
                } catch (IOException e) {
                    notifyMessage("Error during image notification connection!");
                } finally {
                    try {
                        newImageListenerSocket.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                notifyMessage("No card found, retrying.");
            }
            Thread.sleep(2000);
        }
    } catch (InterruptedException e) {
        stopImageDownLoaderQueue();
        notifyMessage("Connection abandoned.");
    }

}

From source file:com.cws.esolutions.core.utils.NetworkUtils.java

/**
 * Creates an telnet connection to a target host and port number. Silently
 * succeeds if no issues are encountered, if so, exceptions are logged and
 * re-thrown back to the requestor./*from ww  w  .  j a v  a2 s .  com*/
 *
 * If an exception is thrown during the <code>socket.close()</code> operation,
 * it is logged but NOT re-thrown. It's not re-thrown because it does not indicate
 * a connection failure (indeed, it means the connection succeeded) but it is
 * logged because continued failures to close the socket could result in target
 * system instability.
 * 
 * @param hostName - The target host to make the connection to
 * @param portNumber - The port number to attempt the connection on
 * @param timeout - The timeout for the connection
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 */
public static final synchronized void executeTelnetRequest(final String hostName, final int portNumber,
        final int timeout) throws UtilityException {
    final String methodName = NetworkUtils.CNAME
            + "#executeTelnetRequest(final String hostName, final int portNumber, final int timeout) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug(hostName);
        DEBUGGER.debug("portNumber: {}", portNumber);
        DEBUGGER.debug("timeout: {}", timeout);
    }

    Socket socket = null;

    try {
        synchronized (new Object()) {
            if (InetAddress.getByName(hostName) == null) {
                throw new UnknownHostException("No host was found in DNS for the given name: " + hostName);
            }

            InetSocketAddress socketAddress = new InetSocketAddress(hostName, portNumber);

            socket = new Socket();
            socket.setSoTimeout((int) TimeUnit.SECONDS.toMillis(timeout));
            socket.setSoLinger(false, 0);
            socket.setKeepAlive(false);
            socket.connect(socketAddress, (int) TimeUnit.SECONDS.toMillis(timeout));

            if (!(socket.isConnected())) {
                throw new ConnectException("Failed to connect to host " + hostName + " on port " + portNumber);
            }

            PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true);

            pWriter.println(NetworkUtils.TERMINATE_TELNET + NetworkUtils.CRLF);

            pWriter.flush();
            pWriter.close();
        }
    } catch (ConnectException cx) {
        throw new UtilityException(cx.getMessage(), cx);
    } catch (UnknownHostException ux) {
        throw new UtilityException(ux.getMessage(), ux);
    } catch (SocketException sx) {
        throw new UtilityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        throw new UtilityException(iox.getMessage(), iox);
    } finally {
        try {
            if ((socket != null) && (!(socket.isClosed()))) {
                socket.close();
            }
        } catch (IOException iox) {
            // log it - this could cause problems later on
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }
    }
}

From source file:com.meidusa.venus.io.network.VenusBIOConnectionFactory.java

public VenusBIOConnection makeObject() throws Exception {
    Socket socket = new Socket();
    InetSocketAddress address = null;
    if (host == null) {
        address = new InetSocketAddress(port);
    } else {//from w  w  w  . j  a  v a  2 s . c  o m
        address = new InetSocketAddress(host, port);
    }

    socket.setSendBufferSize(sendBufferSize * 1024);
    socket.setReceiveBufferSize(receiveBufferSize * 1024);
    socket.setTcpNoDelay(tcpNoDelay);
    socket.setKeepAlive(keepAlive);
    try {
        if (soTimeout > 0) {
            socket.setSoTimeout(soTimeout);
        }
        if (coTimeout > 0) {
            socket.connect(address, coTimeout);
        } else {
            socket.connect(address);
        }
    } catch (ConnectException e) {
        throw new ConnectException(e.getMessage() + " " + address.getHostName() + ":" + address.getPort());
    }

    VenusBIOConnection conn = new VenusBIOConnection(socket, TimeUtil.currentTimeMillis());
    byte[] bts = conn.read();
    HandshakePacket handshakePacket = new HandshakePacket();
    handshakePacket.init(bts);

    AuthenPacket authen = getAuthenticator().createAuthenPacket(handshakePacket);
    conn.write(authen.toByteArray());
    bts = conn.read();
    int type = AbstractServicePacket.getType(bts);
    if (type == PacketConstant.PACKET_TYPE_OK) {
        if (authenticatorLogger.isInfoEnabled()) {
            authenticatorLogger.info("authenticated by server=" + host + ":" + port + " success");
        }
    } else if (type == PacketConstant.PACKET_TYPE_ERROR) {
        ErrorPacket error = new ErrorPacket();
        error.init(bts);
        if (authenticatorLogger.isInfoEnabled()) {
            authenticatorLogger.info("authenticated by server=" + host + ":" + port + " error={code="
                    + error.errorCode + ",message=" + error.message + "}");
        }
        throw new AuthenticationException(error.message, error.errorCode);
    }

    return conn;
}

From source file:org.darkphoenixs.pool.socket.SocketConnectionFactory.java

@Override
public Socket createConnection() throws Exception {

    Socket socket = new Socket();

    try {/*from   w ww . j  av  a  2 s .c o m*/
        if (sendBufferSize > 0)
            socket.setSendBufferSize(sendBufferSize);

        if (receiveBufferSize > 0)
            socket.setReceiveBufferSize(receiveBufferSize);

        if (soTimeout > 0)
            socket.setSoTimeout(soTimeout);

        if (linger > 0)
            socket.setSoLinger(true, linger);

        if (keepAlive)
            socket.setKeepAlive(keepAlive);

        if (tcpNoDelay)
            socket.setTcpNoDelay(tcpNoDelay);

        if (performance != null)
            socket.setPerformancePreferences(Integer.parseInt(performance[0]), Integer.parseInt(performance[1]),
                    Integer.parseInt(performance[2]));

        socket.connect(socketAddress, connectionTimeout);

    } catch (Exception se) {
        socket.close();
        throw se;
    }

    return socket;
}

From source file:com.cws.esolutions.core.utils.NetworkUtils.java

/**
 * Creates an telnet connection to a target host and port number. Silently
 * succeeds if no issues are encountered, if so, exceptions are logged and
 * re-thrown back to the requestor.//from   w ww . j a v a  2s.c o  m
 *
 * If an exception is thrown during the <code>socket.close()</code> operation,
 * it is logged but NOT re-thrown. It's not re-thrown because it does not indicate
 * a connection failure (indeed, it means the connection succeeded) but it is
 * logged because continued failures to close the socket could result in target
 * system instability.
 * 
 * @param hostName - The target host to make the connection to
 * @param portNumber - The port number to attempt the connection on
 * @param timeout - How long to wait for a connection to establish or a response from the target
 * @param object - The serializable object to send to the target
 * @return <code>Object</code> as output from the request
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 */
public static final synchronized Object executeTcpRequest(final String hostName, final int portNumber,
        final int timeout, final Object object) throws UtilityException {
    final String methodName = NetworkUtils.CNAME
            + "#executeTcpRequest(final String hostName, final int portNumber, final int timeout, final Object object) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug(hostName);
        DEBUGGER.debug("portNumber: {}", portNumber);
        DEBUGGER.debug("timeout: {}", timeout);
        DEBUGGER.debug("object: {}", object);
    }

    Socket socket = null;
    Object resObject = null;

    try {
        synchronized (new Object()) {
            if (StringUtils.isEmpty(InetAddress.getByName(hostName).toString())) {
                throw new UnknownHostException("No host was found in DNS for the given name: " + hostName);
            }

            InetSocketAddress socketAddress = new InetSocketAddress(hostName, portNumber);

            socket = new Socket();
            socket.setSoTimeout((int) TimeUnit.SECONDS.toMillis(timeout));
            socket.setSoLinger(false, 0);
            socket.setKeepAlive(false);
            socket.connect(socketAddress, (int) TimeUnit.SECONDS.toMillis(timeout));

            if (!(socket.isConnected())) {
                throw new ConnectException("Failed to connect to host " + hostName + " on port " + portNumber);
            }

            ObjectOutputStream objectOut = new ObjectOutputStream(socket.getOutputStream());

            if (DEBUG) {
                DEBUGGER.debug("ObjectOutputStream: {}", objectOut);
            }

            objectOut.writeObject(object);

            resObject = new ObjectInputStream(socket.getInputStream()).readObject();

            if (DEBUG) {
                DEBUGGER.debug("resObject: {}", resObject);
            }

            PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true);

            pWriter.println(NetworkUtils.TERMINATE_TELNET + NetworkUtils.CRLF);

            pWriter.flush();
            pWriter.close();
        }
    } catch (ConnectException cx) {
        throw new UtilityException(cx.getMessage(), cx);
    } catch (UnknownHostException ux) {
        throw new UtilityException(ux.getMessage(), ux);
    } catch (SocketException sx) {
        throw new UtilityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        throw new UtilityException(iox.getMessage(), iox);
    } catch (ClassNotFoundException cnfx) {
        throw new UtilityException(cnfx.getMessage(), cnfx);
    } finally {
        try {
            if ((socket != null) && (!(socket.isClosed()))) {
                socket.close();
            }
        } catch (IOException iox) {
            // log it - this could cause problems later on
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }
    }

    return resObject;
}

From source file:com.epam.reportportal.apache.http.impl.conn.HttpClientConnectionOperator.java

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");
    }/*from   w  w w  . j a va  2  s  .co  m*/
    final InetAddress[] addresses = 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.setReuseAddress(socketConfig.isSoReuseAddress());
        conn.bind(sock);

        final InetSocketAddress remoteAddress = new InetSocketAddress(address, port);
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connecting to " + remoteAddress);
        }
        try {
            sock.setSoTimeout(socketConfig.getSoTimeout());
            sock = sf.connectSocket(connectTimeout, sock, host, remoteAddress, localAddress, context);
            sock.setTcpNoDelay(socketConfig.isTcpNoDelay());
            sock.setKeepAlive(socketConfig.isSoKeepAlive());
            final int linger = socketConfig.getSoLinger();
            if (linger >= 0) {
                sock.setSoLinger(linger > 0, linger);
            }
            conn.bind(sock);
            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);
                }
            }
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connect to " + remoteAddress + " timed out. "
                    + "Connection will be retried using another IP address");
        }
    }
}

From source file:org.apache.http.impl.conn.HttpClientConnectionOperator.java

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");
    }//from   ww w .  j av  a2 s  . co  m
    final InetAddress[] addresses = 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.setReuseAddress(socketConfig.isSoReuseAddress());
        conn.bind(sock);

        final InetSocketAddress remoteAddress = new InetSocketAddress(address, port);
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connecting to " + remoteAddress);
        }
        try {
            sock.setSoTimeout(socketConfig.getSoTimeout());
            sock = sf.connectSocket(connectTimeout, sock, host, remoteAddress, localAddress, context);
            sock.setTcpNoDelay(socketConfig.isTcpNoDelay());
            sock.setKeepAlive(socketConfig.isSoKeepAlive());
            final int linger = socketConfig.getSoLinger();
            if (linger >= 0) {
                sock.setSoLinger(linger > 0, linger);
            }
            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);
                }
            }
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connect to " + remoteAddress + " timed out. "
                    + "Connection will be retried using another IP address");
        }
    }
}

From source file:hudson.TcpSlaveAgentListener.java

@Override
public void run() {
    try {//from  w ww .  j av  a  2s.  com
        // the loop eventually terminates when the socket is closed.
        while (!shuttingDown) {
            Socket s = serverSocket.accept().socket();

            // this prevents a connection from silently terminated by the router in between or the other peer
            // and that goes without unnoticed. However, the time out is often very long (for example 2 hours
            // by default in Linux) that this alone is enough to prevent that.
            s.setKeepAlive(true);
            // we take care of buffering on our own
            s.setTcpNoDelay(true);

            new ConnectionHandler(s, new ConnectionHandlerFailureCallback(this) {
                @Override
                public void run(Throwable cause) {
                    LOGGER.log(Level.WARNING, "Connection handler failed, restarting listener", cause);
                    shutdown();
                    TcpSlaveAgentListenerRescheduler.schedule(getParentThread(), cause);
                }
            }).start();
        }
    } catch (IOException e) {
        if (!shuttingDown) {
            LOGGER.log(Level.SEVERE, "Failed to accept TCP connections", e);
        }
    }
}

From source file:org.springframework.integration.ip.tcp.connection.AbstractConnectionFactory.java

/**
 * Sets socket attributes on the socket.
 * @param socket The socket./* ww w  . ja  v  a 2 s.  c  o  m*/
 * @throws SocketException
 */
protected void setSocketAttributes(Socket socket) throws SocketException {
    if (this.soTimeout >= 0) {
        socket.setSoTimeout(this.soTimeout);
    }
    if (this.soSendBufferSize > 0) {
        socket.setSendBufferSize(this.soSendBufferSize);
    }
    if (this.soReceiveBufferSize > 0) {
        socket.setReceiveBufferSize(this.soReceiveBufferSize);
    }
    socket.setTcpNoDelay(this.soTcpNoDelay);
    if (this.soLinger >= 0) {
        socket.setSoLinger(true, this.soLinger);
    }
    if (this.soTrafficClass >= 0) {
        socket.setTrafficClass(this.soTrafficClass);
    }
    socket.setKeepAlive(this.soKeepAlive);
}

From source file:com.clavain.munin.MuninNode.java

public void run() {
    b_isRunning = true;//from   w w  w.  j a v a2  s  . co  m

    if (this.str_via.equals("unset")) {
        logger.info(getHostname() + " Monitoring job started");
    } else {
        logger.info(getHostname() + " (VIA: " + this.str_via + ") Monitoring job started");
    }

    int iCurTime = getUnixtime();
    int iPluginRefreshTime = last_plugin_load + Integer.parseInt(p.getProperty("plugin.refreshtime"));
    try {
        // update plugins, maybe we have some new :)
        // double try to load plugins if fail

        if (getPluginList().size() > 0) {
            if (!is_init) {
                logger.info("[Job: " + getHostname() + "] Updating Database");
                // update graphs in database too
                for (MuninPlugin it_pl : getPluginList()) {
                    if (it_pl.getGraphs().size() > 0) {
                        //logger.info(it_pl.getPluginName());
                        dbUpdatePluginForNode(getNode_id(), it_pl);
                    }
                }
                // delete now missing plugins
                dbDeleteMissingPlugins(getNode_id(), getPluginList());
                logger.info("[Job: " + getHostname() + "] Databaseupdate Done");
                is_init = true;
            } else {
                if (iCurTime > iPluginRefreshTime) {
                    logger.info("Refreshing Plugins on " + this.getHostname());
                    this.loadPlugins();
                    dbUpdateAllPluginsForNode(this);
                }
            }
        } else {
            this.loadPlugins();
        }

        Socket clientSocket = new Socket();
        clientSocket.setSoTimeout(com.clavain.muninmxcd.socketTimeout);
        clientSocket.setKeepAlive(false);
        clientSocket.setReuseAddress(true);
        if (this.str_via.equals("unset")) {
            clientSocket.connect(new InetSocketAddress(this.getHostname(), this.getPort()),
                    com.clavain.muninmxcd.socketTimeout);
        } else {
            clientSocket.connect(new InetSocketAddress(this.getStr_via(), this.getPort()),
                    com.clavain.muninmxcd.socketTimeout);
        }
        lastSocket = clientSocket;
        SocketCheck sc = new SocketCheck(clientSocket, getUnixtime());
        if (p.getProperty("kill.sockets").equals("true")) {
            sc.setHostname(this.getHostname());
            com.clavain.muninmxcd.v_sockets.add(sc);
        }
        this.i_lastRun = getUnixtime();

        // track packages?
        if (this.track_pkg) {
            updateTrackPackages(clientSocket);
        }

        // gather essentials?
        if (this.essentials) {
            updateEssentials(clientSocket);
        }

        // update graphs for all plugins
        Iterator it = this.getLoadedPlugins().iterator();
        while (it.hasNext()) {
            MuninPlugin l_mp = (MuninPlugin) it.next();
            if (logMore) {
                logger.info(getHostname() + " fetching graphs for " + l_mp.getPluginName().toUpperCase());
            }
            // snmp support
            if (!str_via.equals("unset")) {
                l_mp.updateAllGraps(this.getStr_via(), this.getPort(), clientSocket, getQueryInterval());
            } else {
                l_mp.updateAllGraps(this.getHostname(), this.getPort(), clientSocket, getQueryInterval());
            }
            // add all graphs to insertion queue for mongodb
            queuePluginFetch(l_mp.returnAllGraphs(), l_mp.getPluginName());
        }
        clientSocket.close();

        if (p.getProperty("kill.sockets").equals("true")) {
            com.clavain.muninmxcd.v_sockets.remove(sc);
        }
        sc = null;
    } catch (Exception ex) {
        logger.fatal("Error in thread for host: " + getHostname() + " : " + ex.getLocalizedMessage());
        ex.printStackTrace();
    }
    int iRunTime = getUnixtime() - iCurTime;
    dbUpdateLastContact(this.getNode_id());
    logger.info(getHostname() + " Monitoring job stopped - runtime: " + iRunTime);

}