Example usage for java.net ServerSocket ServerSocket

List of usage examples for java.net ServerSocket ServerSocket

Introduction

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

Prototype

public ServerSocket(int port) throws IOException 

Source Link

Document

Creates a server socket, bound to the specified port.

Usage

From source file:uk.ac.soton.itinnovation.sad.service.services.EccIntegrationService.java

public boolean start() {

    logger.debug("Initialising ECC Integration service");
    createdProcesses = new ArrayList<>();

    boolean result = true;

    // If ECC intagration enabled
    if (!configurationService.getConfiguration().isEccEnabled()) {
        logger.debug("Nothing to do, ECC integration disabled");

    } else {/*from ww w .  j a  v a 2 s. c  o m*/

        // Discover plugins
        JSONObject pluginInfo;
        String pathToPlugins = pluginsService.getAbsolutePluginsPath();
        JSONObject currentSadConfig = JSONObject.fromObject(configurationService.getConfiguration());
        String configurationFilePath;
        try {
            File tmp = File.createTempFile("sadconfiguration", ".json");
            tmp.deleteOnExit();

            File coordinatorPath = new File(configurationService.getConfiguration().getCoordinatorPath());

            currentSadConfig.put("coordinatorPathAbs", coordinatorPath.getAbsolutePath());

            FileWriter fileWriter = new FileWriter(tmp);
            fileWriter.write(currentSadConfig.toString());
            fileWriter.close();
            configurationFilePath = tmp.getAbsolutePath();
            logger.debug("Stored current configuration for plugins\n" + currentSadConfig.toString(2) + "\nin: "
                    + configurationFilePath);
        } catch (IOException e) {
            logger.error("Failed to create temporary configuration file", e);
            return false;
        }
        ServerSocket s;

        Thread tempThread;
        int pluginCounter = 0;
        for (String pluginName : pluginsService.getPluginNames()) {

            pluginCounter++;

            logger.debug("Processing plugin " + pluginCounter + ": " + pluginName);
            pluginInfo = pluginsService.getPluginByName(pluginName);

            if (pluginInfo.isEmpty()) {
                logger.error("Plugin not found: " + pluginName);
                continue;
            }

            if (!pluginInfo.containsKey("paths")) {
                logger.error(
                        "Plugin configuration must contain \'paths\'. Misconfigured plugin: " + pluginName);
                continue;
            }

            if (!pluginInfo.containsKey("pluginFolder")) {
                logger.error(
                        "Plugin configuration must be loaded with pluginsService that fills in the \'pluginFolder\' field. Misconfigured plugin: "
                                + pluginName);
                continue;
            }

            JSONObject pluginPaths = pluginInfo.getJSONObject("paths");

            if (!pluginPaths.containsKey("jar")) {
                logger.error(
                        "Plugin configuration must contain \'paths/jar\'. Misconfigured plugin: " + pluginName);
                continue;
            }
            if (!pluginPaths.containsKey("dependenciesFolder")) {
                logger.error(
                        "Plugin configuration must contain \'paths/dependenciesFolder\'. Misconfigured plugin: "
                                + pluginName);
                continue;
            }
            if (!pluginInfo.containsKey("pluginFolder")) {
                logger.error("Plugin configuration must contain \'pluginFolder\'. Misconfigured plugin: "
                        + pluginName);
                continue;
            }

            //                portNumber++;
            String jarPath = pluginPaths.getString("jar");
            String dependenciesFolderPath = pluginPaths.getString("dependenciesFolder");
            String pluginFolder = pluginInfo.getString("pluginFolder");
            String port = null;
            try {
                s = new ServerSocket(0);
                port = Integer.toString(s.getLocalPort());
                s.close();
            } catch (IOException ex) {
                logger.error("Failed to assign a new free port", ex);
                throw new RuntimeException(ex);
            }

            String uuid = configurationService.getConfiguration().getEcc().getClientsUuuidSeed()
                    + Integer.toHexString(pluginCounter);
            logger.debug("Using seeded UUID: " + uuid);

            logger.debug("Plugin jar path from configuration: " + jarPath + ", dependenciesFolderPath: "
                    + dependenciesFolderPath);
            logger.debug("Plugin folder configuration: " + pathToPlugins);
            logger.debug("Socket port: " + port);
            logger.debug("ECC client UUID: " + uuid);

            String[] command = new String[] { "java", "-cp",
                    pathToPlugins + fileSeparator + pluginFolder + fileSeparator + dependenciesFolderPath
                            + fileSeparator + "*",
                    "-jar", pathToPlugins + fileSeparator + pluginFolder + fileSeparator + jarPath, "ecc",
                    configurationFilePath, port, uuid };

            StringBuilder commandSb = new StringBuilder();
            for (String c : command) {
                commandSb.append(c);
                commandSb.append(" ");
            }
            String commandAsString = commandSb.toString();

            logger.debug("Launching ECC part of '" + pluginName + "' plugin with command: " + commandAsString
                    + " on port: " + port);

            pluginNamesAndPorts.put(pluginName, port);

            try {
                Process p = Runtime.getRuntime().exec(command);
                tempThread = new Thread(new ProcessWatcher(p));
                tempThread.start();
                createdProcesses.add(p);

            } catch (Throwable ex) {
                logger.error("Failed to start ECC part of '" + pluginName + "' plugin", ex);
                result = false;
            }
        }

    }

    return result;
}

From source file:com.chinamobile.bcbsp.pipes.Application.java

/**
 * This method is the constructor.//w w  w.  j  av a  2 s  . c o  m
 * @param job
 *        contains BSPJob configuration
 * @param processType
 *        the type of c++ process(for staff or workmanager)
 * @param jobCpath
 *        c++ executable file path
 */
public Application(BSPJob job, String processType, String jobCpath) throws IOException, InterruptedException {
    serverSocket = new ServerSocket(0);
    Map<String, String> env = new HashMap<String, String>();
    env.put("TMPDIR", System.getProperty("java.io.tmpdir"));
    env.put("bcbsp.pipes.command.port", Integer.toString(serverSocket.getLocalPort()));
    env.put("processType", processType);
    String bcbspdir = job.getConf().get("bcbsp.log.dir");
    LOG.info("bcbsp log dir : " + bcbspdir);
    env.put("bcbsp.log.dir", bcbspdir);
    List<String> cmd = new ArrayList<String>();
    String executable = jobCpath;
    LOG.info("processType is :" + processType);
    LOG.info("executable is :" + executable);
    // String executable = job.getJobExe();
    FileUtil.chmod(executable, "a+x");
    cmd.add(executable);
    process = runClient(cmd, env);
    clientSocket = serverSocket.accept();
    this.handler = new TaskHandler();
    this.downlink = new BinaryProtocol(clientSocket, handler);
    this.downlink.start();
}

From source file:hudson.gridmaven.gridlayer.PluginImpl.java

/**
 * Compute the host name that Hadoop nodes can be used to talk to Name node.
 *
 * <p>//  w  w w .  j av  a 2  s .  com
 * We prefer to use {@link Hudson#getRootUrl()}, except we have to watch out for a possibility
 * that it points to a front end (like apache, router with port-forwarding, etc.), and if that is the case,
 * use some heuristics to find out a usable host name.
 *
 * TODO: move this to {@code Hudson.toComputer().getHostName()}. 
 */
String getMasterHostName() throws IOException, InterruptedException {
    // check if rootURL is reliable
    Hudson h = Hudson.getInstance();
    String rootUrl = h.getRootUrl();
    if (rootUrl == null) {
        // the only option is to auto-detect.
        String real = h.toComputer().getHostName();
        LOGGER.fine("Hudson root URL isn't configured. Using " + real + " instead");
        return real;
    }

    // according to Hudson's setting, this is the host name that we can use to connect to master,
    // at least for HTTP. See if we can connect to the arbitrary port in this way.
    final String hostName = new URL(rootUrl).getHost();
    final ServerSocket ss = new ServerSocket(0);

    Thread t = new Thread() {
        @Override
        public void run() {
            try {
                ss.accept();
            } catch (IOException e) {
                // shouldn't happen
                LOGGER.log(Level.INFO, "Failed to accept", e);
            } finally {
                try {
                    ss.close();
                } catch (IOException e) {
                    // ignore
                }
            }
        }
    };
    t.start();

    try {
        Socket s = new Socket();
        s.connect(new InetSocketAddress(hostName, ss.getLocalPort()), 1000);
        s.close();

        // yep, it worked
        return hostName;
    } catch (IOException e) {
        // no it didn't
        String real = h.toComputer().getHostName();
        LOGGER.fine("Hudson root URL " + rootUrl + " looks like a front end. Using " + real + " instead");
        return real;
    }
}

From source file:com.dbmojo.DBMojoServer.java

private static DBMojoServer getMojoServerFromConfig(String[] args) {

    DBMojoServer server = null;// ww w  .j a v  a  2 s .c  o m

    try {
        String configFilePath = null;
        String json = null;
        JSONObject jObj = null;

        parseJson: {
            //If a command line argument is passed then assume it is the config file.
            //Otherwise use the default location
            if (args.length > 0) {
                configFilePath = args[0];
            } else {
                configFilePath = DBMojoServer.defaultConfigPath;
            }

            try {
                json = Util.fileToString(configFilePath);
            } catch (Exception fileEx) {
                throw new Exception(
                        "the specified config file, '" + configFilePath + "', could not be found and/or read");
            }

            if (json == null || json.equals("")) {
                throw new Exception("the specified config file, '" + configFilePath + "', is empty");
            }

            try {
                jObj = new JSONObject(json);
            } catch (Exception je) {
                throw new Exception(
                        "the specified config file, '" + configFilePath + "', does not contain valid JSON");
            }
        }

        //Load basic config data
        short serverPort = (short) jObj.optInt("serverPort");
        boolean useGzip = jObj.optBoolean("useGzip");
        short maxConcReq = (short) jObj.optInt("maxConcurrentRequests");
        String accessLogPath = jObj.optString("accessLogPath");
        String errorLogPath = jObj.optString("errorLogPath");
        String debugLogPath = jObj.optString("debugLogPath");

        checkMaxConcurrentReqeusts: {
            if (maxConcReq <= 0) {
                throw new Exception("please set the max concurrent requests to " + "a resonable number");
            }
        }

        checkServerPort: {
            //Make sure serverPort was specified
            if (serverPort <= 0) {
                throw new Exception("the server port was not specified");
            }

            //Make sure serverPort is not in use
            ServerSocket tSocket = null;
            try {
                tSocket = new ServerSocket(serverPort);
            } catch (Exception se) {
                tSocket = null;
                throw new Exception("the server port specified is already in use");
            } finally {
                if (tSocket != null) {
                    tSocket.close();
                }
                tSocket = null;
            }
        }

        startLogs: {
            if (!accessLogPath.equals("")) {
                //Make sure accessLogPath exists
                Util.pathExists(accessLogPath, true);
                //Start logging
                AccessLog.start(accessLogPath);
            }

            if (!errorLogPath.equals("")) {
                //Make sure errorLogPath exists
                Util.pathExists(errorLogPath, true);
                //Start logging
                ErrorLog.start(errorLogPath);
            }

            if (!debugLogPath.equals("")) {
                //Make sure debugLogPath exists
                Util.pathExists(debugLogPath, true);
                //Start logging
                DebugLog.start(debugLogPath);
            }
        }

        ConcurrentHashMap<String, ConnectionPool> dbPools = new ConcurrentHashMap<String, ConnectionPool>();
        loadDbAlaises: {
            ClassLoader classLoader = ClassLoader.getSystemClassLoader();
            final JSONArray dbAliases = jObj.getJSONArray("dbAliases");

            for (int i = 0; i < dbAliases.length(); i++) {
                final JSONObject tObj = dbAliases.getJSONObject(i);
                final String tAlias = tObj.getString("alias");
                final String tDriver = tObj.getString("driver");
                final String tDsn = tObj.getString("dsn");
                final String tUsername = tObj.getString("username");
                final String tPassword = tObj.getString("password");
                int tMaxConnections = tObj.getInt("maxConnections");
                //Seconds
                int tExpirationTime = tObj.getInt("expirationTime") * 1000;
                //Seconds
                int tConnectTimeout = tObj.getInt("connectTimeout");

                //Make sure each alias is named
                if (tAlias.equals("")) {
                    throw new Exception("alias #" + i + " is missing a name");
                }

                //Attempt to load each JDBC driver to ensure they are on the class path
                try {
                    Class aClass = classLoader.loadClass(tDriver);
                } catch (ClassNotFoundException cnf) {
                    throw new Exception("JDBC Driver '" + tDriver + "' is not on the class path");
                }

                //Make sure each alias has a JDBC connection string
                if (tDsn.equals("")) {
                    throw new Exception("JDBC URL, 'dsn', is missing for alias '" + tAlias + "'");
                }

                //Attempt to create a JDBC Connection
                ConnectionPool tPool;
                try {
                    tPool = new JDBCConnectionPool(tDriver, tDsn, tUsername, tPassword, 1, 1, 1, tAlias);
                    tPool.checkOut(false);
                } catch (Exception e) {
                    throw new Exception(
                            "JDBC Connection cannot be established " + "for database '" + tAlias + "'");
                } finally {
                    tPool = null;
                }

                //If the max connections option is not set for this alias 
                //then set it to 25
                if (tMaxConnections <= 0) {
                    tMaxConnections = 25;
                    System.out.println("DBMojoServer: Warning, 'maxConnections' " + "not set for alias '"
                            + tAlias + "' using 25");
                }

                //If the connection expiration time is not set for this alias then 
                //set it to 30 seconds
                if (tExpirationTime <= 0) {
                    tExpirationTime = 30;
                    System.out.println("DBMojoServer: Warning, 'expirationTime' not " + "set for alias '"
                            + tAlias + "' using 30 seconds");
                }

                //If the connection timeout is not set for this alias then 
                //set it to 10 seconds
                if (tConnectTimeout <= 0) {
                    tConnectTimeout = 10;
                    System.out.println("DBMojoServer Warning, 'connectTimeout' not " + "set for alias '"
                            + tAlias + "' using 10 seconds");
                }

                //Make sure another alias with the same name is not already 
                //defined in the config
                if (dbPools.containsKey(tAlias)) {
                    throw new Exception(
                            "the alias '" + tAlias + "' is already defined in " + " the provided config file");
                }

                //Everything is nicely set! Lets add a connection pool to the 
                //dbPool Hashtable keyed by this alias name
                dbPools.put(tAlias, new JDBCConnectionPool(tDriver, tDsn, tUsername, tPassword, tMaxConnections,
                        tExpirationTime, tConnectTimeout, tAlias));
            }
        }

        loadClusters: {
            final JSONArray tClusters = jObj.optJSONArray("clusters");

            if (tClusters != null) {
                for (int c = 0; c < tClusters.length(); c++) {
                    final JSONObject tObj = tClusters.getJSONObject(c);
                    final String tAlias = tObj.getString("alias");
                    final String tWriteTo = tObj.getString("writeTo");

                    if (dbPools.containsKey(tAlias)) {
                        throw new Exception("the alias '" + tAlias + "' is already defined.");
                    }

                    if (!dbPools.containsKey(tWriteTo)) {
                        throw new Exception(
                                "the alias '" + tWriteTo + "' is not present in the valid dbAliases. "
                                        + "This alias cannot be used for a cluster.");
                    }

                    //Add the dbAlias to the cluster writeTo list
                    ConnectionPool writeTo = dbPools.get(tWriteTo);

                    final JSONArray tReadFrom = tObj.getJSONArray("readFrom");
                    ArrayList<ConnectionPool> readFromList = new ArrayList<ConnectionPool>();
                    for (int r = 0; r < tReadFrom.length(); r++) {
                        final String tRead = tReadFrom.getString(r);
                        if (!dbPools.containsKey(tRead)) {
                            throw new Exception(
                                    "the alias '" + tRead + "' is not present in the valid dbAliases. "
                                            + "This alias cannot be used for a cluster.");
                        }
                        //Add the dbAlias to the cluster readFrom list
                        readFromList.add(dbPools.get(tRead));
                    }

                    dbPools.put(tAlias, new JDBCClusteredConnectionPool(tAlias, writeTo, readFromList));
                }
            }
        }

        server = new DBMojoServer(useGzip, serverPort, maxConcReq, dbPools);

    } catch (Exception jsonEx) {
        System.out.println("DBMojoServer: Config error, " + jsonEx);
        System.exit(-1);
    }

    return server;
}

From source file:com.feedzai.fos.impl.weka.WekaManager.java

/**
 * Create a new manager from the given configuration.
 * <p/> Will lookup any headers files and to to instantiate the model.
 * <p/> If a model fails, a log is produced but loading other models will continue (no exception is thrown).
 *
 * @param wekaManagerConfig the manager configuration
 *//*from   w w  w . j a  v a 2s . co m*/
public WekaManager(WekaManagerConfig wekaManagerConfig) {
    checkNotNull(wekaManagerConfig, "Manager config cannot be null");

    this.wekaManagerConfig = wekaManagerConfig;

    Collection<File> headers = FileUtils.listFiles(wekaManagerConfig.getHeaderLocation(),
            new String[] { WekaManagerConfig.HEADER_EXTENSION }, true);
    for (File header : headers) {
        logger.trace("Reading model file '{}'", header);

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(header);
            String modelConfigJson = IOUtils.toString(fileInputStream);

            ModelConfig modelConfig = mapper.readValue(modelConfigJson, ModelConfig.class);
            WekaModelConfig wekaModelConfig = new WekaModelConfig(modelConfig, wekaManagerConfig);
            wekaModelConfig.setHeader(header);
            wekaModelConfig.setDirty(false /* not changed so far */);

            if (modelConfigs.containsKey(wekaModelConfig.getId())) {
                logger.error(
                        "Model with ID '{}' is duplicated in the configuration (the configuration from '{}' is discarded)",
                        wekaModelConfig.getId(), header.getAbsolutePath());
            } else {
                modelConfigs.put(wekaModelConfig.getId(), wekaModelConfig);
            }
        } catch (Exception e) {
            logger.error("Could not load from '{}' (continuing to load others)", header, e);
        } finally {
            IOUtils.closeQuietly(fileInputStream);
        }
    }

    this.wekaScorer = new WekaScorer(modelConfigs, wekaManagerConfig);

    try {
        int port = wekaManagerConfig.getScoringPort();
        this.serverSocket = new ServerSocket(port);
        serverSocket.setReuseAddress(true);
        final int max_threads = wekaManagerConfig.getMaxSimultaneousScoringThreads();
        Runnable acceptRunnable = new Runnable() {
            ExecutorService executor = Executors.newFixedThreadPool(max_threads);

            @Override
            public void run() {
                acceptThreadRunning = true;
                try {
                    while (acceptThreadRunning && Thread.currentThread().isInterrupted() == false) {
                        Socket client = serverSocket.accept();
                        client.setTcpNoDelay(true);
                        scorerHandler = new KryoScoringEndpoint(client, wekaScorer);
                        executor.submit(scorerHandler);
                    }
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        };
        acceptThread = new Thread(acceptRunnable);
        acceptThread.start();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:com.jredrain.startup.Bootstrap.java

private void await() throws Exception {
    // Negative values - don't wait on port - redrain is embedded or we just don't like ports
    if (port == -2) {
        return;/*from   w ww .  j a va2  s. c o  m*/
    }
    if (port == -1) {
        try {
            awaitThread = Thread.currentThread();
            while (!stopAwait) {
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException ex) {
                    // continue and check the flag
                }
            }
        } finally {
            awaitThread = null;
        }
        return;
    }

    // Set up a server socket to wait on
    try {
        awaitSocket = new ServerSocket(RedrainProperties.getInt("redrain.shutdown"));
    } catch (IOException e) {
        logger.error("[redrain] agent .await: create[{}] ", RedrainProperties.getInt("redrain.shutdown"), e);
        return;
    }

    try {
        awaitThread = Thread.currentThread();
        // Loop waiting for a connection and a valid command
        while (!stopAwait) {
            ServerSocket serverSocket = awaitSocket;
            if (serverSocket == null) {
                break;
            }
            // Wait for the next connection
            Socket socket = null;
            StringBuilder command = new StringBuilder();
            try {
                InputStream stream;
                long acceptStartTime = System.currentTimeMillis();
                try {
                    socket = serverSocket.accept();
                    socket.setSoTimeout(10 * 1000); // Ten seconds
                    stream = socket.getInputStream();
                } catch (SocketTimeoutException ste) {
                    // This should never happen but bug 56684 suggests that
                    // it does.
                    logger.warn("[redrain] agentServer accept.timeout",
                            Long.valueOf(System.currentTimeMillis() - acceptStartTime), ste);
                    continue;
                } catch (AccessControlException ace) {
                    logger.warn("[redrain] agentServer .accept security exception: {}", ace.getMessage(), ace);
                    continue;
                } catch (IOException e) {
                    if (stopAwait) {
                        break;
                    }
                    logger.error("[redrain] agent .await: accept: ", e);
                    break;
                }

                // Read a set of characters from the socket
                int expected = 1024; // Cut off to avoid DoS attack
                while (expected < shutdown.length()) {
                    if (random == null) {
                        random = new Random();
                    }
                    expected += (random.nextInt() % 1024);
                }
                while (expected > 0) {
                    int ch = -1;
                    try {
                        ch = stream.read();
                    } catch (IOException e) {
                        logger.warn("[redrain] agent .await: read: ", e);
                        ch = -1;
                    }
                    if (ch < 32) // Control character or EOF terminates loop
                        break;
                    command.append((char) ch);
                    expected--;
                }
            } finally {
                try {
                    if (socket != null) {
                        socket.close();
                    }
                } catch (IOException e) {
                }
            }
            boolean match = command.toString().equals(shutdown);
            if (match) {
                break;
            } else {
                logger.warn("[redrain] agent .await: Invalid command '" + command.toString() + "' received");
            }
        }
    } finally {
        ServerSocket serverSocket = awaitSocket;
        awaitThread = null;
        awaitSocket = null;
        // Close the server socket and return
        if (serverSocket != null) {
            try {
                serverSocket.close();
            } catch (IOException e) {
                // Ignore
            }
        }
    }

}

From source file:com.nike.vault.client.VaultClientTest.java

@Test(expected = VaultClientException.class)
public void write_throws_runtime_exception_if_unexpected_error_encountered() throws IOException {
    final ServerSocket serverSocket = new ServerSocket(0);
    final String vaultUrl = "http://localhost:" + serverSocket.getLocalPort();
    final VaultCredentialsProvider vaultCredentialsProvider = mock(VaultCredentialsProvider.class);
    final OkHttpClient httpClient = buildHttpClient(1, TimeUnit.SECONDS);
    vaultClient = new VaultClient(new StaticVaultUrlResolver(vaultUrl), vaultCredentialsProvider, httpClient);

    when(vaultCredentialsProvider.getCredentials()).thenReturn(new TestVaultCredentials());

    Map<String, String> data = new HashMap<>();
    data.put("key", "value");
    vaultClient.write("app/api-key", data);
}

From source file:net.sf.ehcache.distribution.RMICacheManagerPeerListener.java

/**
 * Gets a free server socket port./*  ww w .java  2s.com*/
 *
 * @return a number in the range 1025 - 65536 that was free at the time this method was executed
 * @throws IllegalArgumentException
 */
protected int getFreePort() throws IllegalArgumentException {
    ServerSocket serverSocket = null;
    try {
        serverSocket = new ServerSocket(0);
        return serverSocket.getLocalPort();
    } catch (IOException e) {
        throw new IllegalArgumentException("Could not acquire a free port number.");
    } finally {
        if (serverSocket != null && !serverSocket.isClosed()) {
            try {
                serverSocket.close();
            } catch (Exception e) {
                LOG.debug("Error closing ServerSocket: " + e.getMessage());
            }
        }
    }
}

From source file:org.apache.flink.streaming.api.functions.sink.SocketClientSinkTest.java

@Test
public void testRetry() throws Exception {

    final ServerSocket[] serverSocket = new ServerSocket[1];
    final ExecutorService[] executor = new ExecutorService[1];

    try {/*w  w  w . j a v  a 2 s.c  o  m*/
        serverSocket[0] = new ServerSocket(0);
        executor[0] = Executors.newCachedThreadPool();

        int port = serverSocket[0].getLocalPort();

        Callable<Void> serverTask = new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                Socket socket = serverSocket[0].accept();

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

                String value = reader.readLine();
                assertEquals("0", value);

                socket.close();
                return null;
            }
        };

        Future<Void> serverFuture = executor[0].submit(serverTask);

        final SocketClientSink<String> sink = new SocketClientSink<>(host, serverSocket[0].getLocalPort(),
                simpleSchema, -1, true);

        // Create the connection
        sink.open(new Configuration());

        // Initial payload => this will be received by the server an then the socket will be
        // closed.
        sink.invoke("0\n");

        // Get future an make sure there was no problem. This will rethrow any Exceptions from
        // the server.
        serverFuture.get();

        // Shutdown the server socket
        serverSocket[0].close();
        assertTrue(serverSocket[0].isClosed());

        // No retries expected at this point
        assertEquals(0, sink.getCurrentNumberOfRetries());

        final CountDownLatch retryLatch = new CountDownLatch(1);
        final CountDownLatch again = new CountDownLatch(1);

        Callable<Void> sinkTask = new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                // Send next payload => server is down, should try to reconnect.

                // We need to send more than just one packet to notice the closed connection.
                while (retryLatch.getCount() != 0) {
                    sink.invoke("1\n");
                }

                return null;
            }
        };

        Future<Void> sinkFuture = executor[0].submit(sinkTask);

        while (sink.getCurrentNumberOfRetries() == 0) {
            // Wait for a retry
            Thread.sleep(100);
        }

        // OK the poor guy retried to write
        retryLatch.countDown();

        // Restart the server
        serverSocket[0] = new ServerSocket(port);
        Socket socket = serverSocket[0].accept();

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

        // Wait for the reconnect
        String value = reader.readLine();

        assertEquals("1", value);

        // OK the sink re-connected. :)
    } finally {
        if (serverSocket[0] != null) {
            serverSocket[0].close();
        }

        if (executor[0] != null) {
            executor[0].shutdown();
        }
    }
}

From source file:WebServer.java

/**
 * WebServer constructor./* ww  w . j ava 2s .co m*/
 */
protected void start() {
    ServerSocket s;

    System.out.println("Webserver starting up on port 80");
    System.out.println("(press ctrl-c to exit)");
    try {
        // create the main server socket
        s = new ServerSocket(80);
    } catch (Exception e) {
        System.out.println("Error: " + e);
        return;
    }

    System.out.println("Waiting for connection");
    for (;;) {
        try {
            // wait for a connection
            Socket remote = s.accept();
            // remote is now the connected socket
            System.out.println("Connection, sending data.");
            BufferedReader in = new BufferedReader(new InputStreamReader(remote.getInputStream()));
            PrintWriter out = new PrintWriter(remote.getOutputStream());

            // read the data sent. We basically ignore it,
            // stop reading once a blank line is hit. This
            // blank line signals the end of the client HTTP
            // headers.
            String str = ".";
            while (!str.equals(""))
                str = in.readLine();

            // Send the response
            // Send the headers
            out.println("HTTP/1.0 200 OK");
            out.println("Content-Type: text/html");
            out.println("Server: Bot");
            // this blank line signals the end of the headers
            out.println("");
            // Send the HTML page
            out.println("<H1>Welcome to the Ultra Mini-WebServer</H2>");
            out.flush();
            remote.close();
        } catch (Exception e) {
            System.out.println("Error: " + e);
        }
    }
}