Example usage for java.net ServerSocket setSoTimeout

List of usage examples for java.net ServerSocket setSoTimeout

Introduction

In this page you can find the example usage for java.net ServerSocket setSoTimeout.

Prototype

public synchronized void setSoTimeout(int timeout) throws SocketException 

Source Link

Document

Enable/disable SocketOptions#SO_TIMEOUT SO_TIMEOUT with the specified timeout, in milliseconds.

Usage

From source file:disko.flow.analyzers.socket.SocketReceiver.java

@SuppressWarnings("unchecked")
public void process(C ctx, Ports ports) throws InterruptedException {
    log.debug("Listening to port " + port);
    ServerSocket serverSocket = null;

    try {/*from w w  w . j  a  va  2s .  c  om*/
        serverSocket = new ServerSocket(port);
        serverSocket.setSoTimeout(5000);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    log.debug("Server socket created.");
    Set<OutputPort> closedPorts = new HashSet<OutputPort>();
    try {
        while (closedPorts.size() < ports.getOutputCount()) {
            Message message = readMessage(serverSocket);
            if (message == null)
                break;
            OutputPort output = ports.getOutput(message.getChannelId());
            if (output == null) {
                log.error("OutputPort to channel " + message.getChannelId() + " not found!");
            } else if (message.getData() == null) {
                log.debug("Received EOS of " + message.getChannelId());
                if (!ignoreEOF) {
                    output.close();
                    closedPorts.add(output);
                }
            } else if (output.put(message.getData())) {
                log.debug("Accepted " + message);
            } else {
                closedPorts.add(output);
                log.debug("Ignoring " + message);
            }
        }
    } catch (Throwable t) {
        log.error("Exception at SocketReceiver.", t);
    }
    log.debug("All SocketREceiver outputs closed, exiting normally.");
    try {
        serverSocket.close();
    } catch (Exception ioe) {
        log.error(ioe);
    }
}

From source file:com.twinsoft.convertigo.eclipse.learnproxy.http.HttpProxy.java

public void run() {
    ServerSocket serverSocket = null;
    try {//from www . j  a  v a 2 s  . c o m
        serverSocket = new ServerSocket(proxyPort);
        serverSocket.setSoTimeout(timeout);
        // logger.info("Proxy started at " + proxyPort);
        while (!isStopped) {
            try {
                Socket sock = serverSocket.accept();
                HttpProxyWorker worker = new HttpProxyWorker(this, sock);
                Thread t = new Thread(worker);
                t.start();
            } catch (IOException e) {
                ConvertigoPlugin.logException(e, "Unexpected exception");
            }
        }
    } catch (IOException e) {
        ConvertigoPlugin.logException(e, "Unexpected exception");
    }
}

From source file:org.reficio.cougar.impl.ConnectionFactoryTest.java

private int startMockServer() {
    final int port = TestUtil.getFreePort();
    final CountDownLatch latch = new CountDownLatch(1);
    Runnable runnable = new Runnable() {
        public void run() {
            try {
                ServerSocket srv = new ServerSocket(port, 0, InetAddress.getByName(null));
                latch.countDown();/*from  ww w  .j  a  v a2s . c  om*/
                try {
                    srv.setSoTimeout(15000);
                    Socket comm = srv.accept();
                    Frame response = new Frame(Command.CONNECTED);
                    response.session(UUID.randomUUID().toString());
                    StompWireFormat wireFormat = new WireFormatImpl();
                    OutputStream out = comm.getOutputStream();
                    Writer writer = new OutputStreamWriter(out);
                    wireFormat.marshal(response, writer);
                    writer.close();
                } finally {
                    srv.close();
                }
            } catch (IOException e) {
                log.error("IO exception", e);
            }
        }
    };
    Thread thread = new Thread(runnable);
    thread.start();
    try {
        latch.await();
    } catch (InterruptedException e) {
    }
    return port;
}

From source file:org.openmrs.module.mirebalais.integration.MirthIT.java

private String listenForResults() throws IOException {

    ServerSocket listener = new ServerSocket(6660); // TODO: store this port in a global property?
    listener.setSoTimeout(20000); // don't wait more than 20 seconds for an incoming connection

    Socket mirthConnection = listener.accept();

    BufferedReader reader = new BufferedReader(new InputStreamReader(mirthConnection.getInputStream()));

    StringBuilder sb = new StringBuilder();
    String line;//from   w ww .ja v a  2  s.co  m

    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }

    // TODO: need an acknowledgement?

    mirthConnection.close();
    listener.close();

    return sb.toString();
}

From source file:hudson.remoting.Launcher.java

/**
 * Listens on an ephemeral port, record that port number in a port file,
 * then accepts one TCP connection.//from ww w  .  j  a  v a2s.  co m
 */
private void runAsTcpServer() throws IOException, InterruptedException {
    // if no one connects for too long, assume something went wrong
    // and avoid hanging foreever
    ServerSocket ss = new ServerSocket(0, 1);
    ss.setSoTimeout(30 * 1000);

    // write a port file to report the port number
    FileWriter w = new FileWriter(tcpPortFile);
    w.write(String.valueOf(ss.getLocalPort()));
    w.close();

    // accept just one connection and that's it.
    // when we are done, remove the port file to avoid stale port file
    Socket s;
    try {
        s = ss.accept();
        ss.close();
    } finally {
        tcpPortFile.delete();
    }

    runOnSocket(s);
}

From source file:com.apporiented.hermesftp.server.AbstractFtpServer.java

/**
 * {@inheritDoc}/*from www . j a  va 2  s  .  c  o  m*/
 */
public void run() {
    setStatus(SERVER_STATUS_INIT);
    ServerSocket serverSocket = null;
    try {
        getUserManager().load();
        serverSocket = createServerSocket();
        serverSocket.setSoTimeout(DEFAULT_TIMEOUT);
        setStatus(SERVER_STATUS_READY);
        while (!isTerminated()) {
            Socket clientSocket;
            try {
                clientSocket = serverSocket.accept();
            } catch (SocketTimeoutException e) {
                continue;
            }

            /* Check blacklisted IP v4 addresses */

            InetAddress clientAddr = clientSocket.getInetAddress();
            InetAddress localAddr = clientSocket.getLocalAddress();

            log.info("Client requests connection. ClientAddr.: " + clientAddr + ", LocalAddr.: " + localAddr);

            String listKey = NetUtils.isIPv6(clientAddr) ? FtpConstants.OPT_IPV6_BLACK_LIST
                    : FtpConstants.OPT_IPV4_BLACK_LIST;
            String ipBlackList = getOptions().getString(listKey, "");

            if (NetUtils.checkIPMatch(ipBlackList, clientAddr)) {
                log.info("Client with IP address " + clientAddr.getHostAddress() + " rejected (blacklisted).");
                IOUtils.closeGracefully(clientSocket);
                continue;
            }

            /* Initialize session context */
            FtpSessionContext ctx = createFtpContext();
            ctx.check();
            ctx.setCreationTime(new Date());
            ctx.setClientSocket(clientSocket);
            FtpSession session = (FtpSession) getApplicationContext().getBean(BEAN_SESSION);
            session.setFtpContext(ctx);

            /* Start session */
            log.debug("Accepting connection to " + clientAddr.getHostAddress());
            session.start();
            registerSession(session);

        }
        setStatus(SERVER_STATUS_HALTED);
    } catch (IOException e) {
        setStatus(SERVER_STATUS_UNDEF);
        log.error(e, e);
    } finally {
        terminateAllClientSessions();
        IOUtils.closeGracefully(serverSocket);
    }

}

From source file:org.apache.axis2.clustering.tribes.WkaBasedMembershipScheme.java

private int getLocalPort(ServerSocket socket, String hostname, int port) throws IOException {
    InetSocketAddress addr;/*from   w  ww.  j a  va 2s  .co  m*/
    addr = new InetSocketAddress(hostname, port);
    socket.bind(addr);
    log.info("Receiver Server Socket bound to:" + addr);
    socket.setSoTimeout(5);
    socket.close();
    try {
        Thread.sleep(100);
    } catch (InterruptedException ignored) {
        ignored.printStackTrace();
    }
    return port;
}

From source file:com.apporiented.hermesftp.cmd.PassiveModeSocketProvider.java

/**
 * Creates the server socket that accepts the data connection.
 * //from  www.ja  va 2 s.c  o  m
 * @param localIp The local IP address.
 * @param port The port.
 * @return The server socket.
 * @throws IOException Error on creating server socket.
 */
private ServerSocket createServerSocket(InetAddress localIp, int port) throws IOException {
    ServerSocket sock;
    Boolean dataProtection = (Boolean) ctx.getAttribute(FtpConstants.ATTR_DATA_PROT);
    boolean ssl = dataProtection != null && dataProtection;
    if (ssl) {
        SSLServerSocketFactory factory = ctx.getOptions().getSslContext().getServerSocketFactory();
        SSLServerSocket sslServerSocket = (SSLServerSocket) factory.createServerSocket(port, 1, localIp);
        sslServerSocket.setUseClientMode(false);
        enableCipherSuites(sslServerSocket);
        sock = sslServerSocket;
    } else {
        sock = ServerSocketFactory.getDefault().createServerSocket(port, 1, localIp);
    }
    sock.setSoTimeout(DATA_CHANNEL_TIMEOUT);
    return sock;
}

From source file:org.apache.isis.objectstore.nosql.db.file.server.FileServer.java

private void startControl() {
    final String controlHost = config.getString("fileserver.control-host", DEFAULT_HOST);
    final int controlPort = config.getInt("fileserver.control-port", DEFAULT_CONTROL_PORT);
    final int connectionTimeout = config.getInt("fileserver.connection.timeout", 5000);

    ServerSocket socket = null;
    try {/*w w w  .  ja  va  2 s.  c o m*/
        LOG.debug("setting up control socket on " + controlHost + ":" + controlPort);
        final InetAddress address = InetAddress.getByName(controlHost);
        socket = new ServerSocket(controlPort, 0, address);
        socket.setSoTimeout(connectionTimeout);
        LOG.info("file control listenting on " + socket.getInetAddress().getHostAddress() + " port "
                + socket.getLocalPort());
        LOG.debug("file control listenting on " + socket);
    } catch (final UnknownHostException e) {
        LOG.error("Unknown host " + controlHost, e);
        System.exit(0);
    } catch (final IOException e) {
        LOG.error("start failure - networking not set up for " + controlHost, e);
        System.exit(0);
    } catch (final RuntimeException e) {
        LOG.error("start failure", e);
        System.exit(0);
    }
    do {
        try {
            final Socket connection = socket.accept();
            LOG.info("control connection from " + connection);
            controlConnection(connection);
        } catch (final SocketTimeoutException expected) {
        } catch (final IOException e) {
            LOG.error("networking problem", e);
        }
    } while (awaitConnections);
}

From source file:org.apache.isis.objectstore.nosql.db.file.server.FileServer.java

private void startService() {
    final String serviceHost = config.getString("fileserver.host", DEFAULT_HOST);
    final int servicePort = config.getInt("fileserver.port", DEFAULT_SERVICE_PORT);
    final int connectionTimeout = config.getInt("fileserver.connection.timeout", 5000);
    final int readTimeout = config.getInt("fileserver.read.timeout", 5000);

    ServerSocket socket = null;
    try {// w w w  . j a v a 2 s  . c om
        LOG.debug("setting up service socket on " + serviceHost + ":" + servicePort);
        final InetAddress address = InetAddress.getByName(serviceHost);
        socket = new ServerSocket(servicePort, BACKLOG, address);
        socket.setSoTimeout(connectionTimeout);
        LOG.info("file service listenting on " + socket.getInetAddress().getHostAddress() + " port "
                + socket.getLocalPort());
        LOG.debug("file service listenting on " + socket);
        final LogRange logFileRange = Util.logFileRange();
        if (!logFileRange.noLogFile()) {
            final long lastRecoveryFile = logFileRange.getLast();
            final File file = Util.logFile(lastRecoveryFile);
            LOG.info("replaying last recovery file: " + file.getAbsolutePath());
            recover(file);
        }
        server.startup();
    } catch (final UnknownHostException e) {
        LOG.error("Unknown host " + serviceHost, e);
        System.exit(0);
    } catch (final IOException e) {
        LOG.error("start failure - networking not set up for " + serviceHost, e);
        System.exit(0);
    } catch (final RuntimeException e) {
        LOG.error("start failure", e);
        System.exit(0);
    }
    do {
        try {
            while (isQuiescent) {
                try {
                    Thread.sleep(300);
                } catch (final InterruptedException ignore) {
                }
            }
            final Socket connection = socket.accept();
            LOG.debug("connection from " + connection);
            connection.setSoTimeout(readTimeout);
            serviceConnection(connection, readTimeout);
        } catch (final SocketTimeoutException expected) {
        } catch (final IOException e) {
            LOG.error("networking problem", e);
        }
    } while (awaitConnections);
}