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:com.dumbster.smtp.SimpleSmtpServer.java

/**
 * Main loop of the SMTP server.// ww  w.jav a  2 s  . co  m
 */
public void run() {
    stopped = false;
    try {
        try {
            serverSocket = new ServerSocket(port);
            serverSocket.setSoTimeout(TIMEOUT); // Block for maximum of 1.5
            // seconds
        } finally {
            synchronized (this) {
                // Notify when server socket has been created
                notifyAll();
            }
        }

        // Server: loop until stopped
        while (!isStopped()) {
            // Start server socket and listen for client connections
            Socket socket = null;
            try {
                socket = serverSocket.accept();
            } catch (Exception e) {
                if (socket != null) {
                    socket.close();
                }
                continue; // Non-blocking socket timeout occurred: try
                          // accept() again
            }

            // Get the input and output streams
            BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream());

            synchronized (this) {
                /*
                 * We synchronize over the handle method and the list update
                 * because the client call completes inside the handle
                 * method and we have to prevent the client from reading the
                 * list until we've updated it. For higher concurrency, we
                 * could just change handle to return void and update the
                 * list inside the method to limit the duration that we hold
                 * the lock.
                 */
                List<SmtpMessage> msgs = handleTransaction(out, input);
                saveMessagesInElasticSearch(msgs);
            }
            socket.close();
        }
    } catch (Exception e) {
        logger.error("Smtp Server could not be started", e);
    } finally {
        if (serverSocket != null) {
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.cloudera.branchreduce.impl.thrift.LordMain.java

@Override
public int run(String[] args) throws Exception {
    LOG.info("Initializing lord...");
    initialize(args);/*from   ww  w .  ja  v a2  s.  c  o m*/
    LOG.info("Lord initialized.");

    String hostname = InetAddress.getLocalHost().getHostName();
    ServerSocket socket = new ServerSocket(0);
    ApplicationMasterParameters appMasterParams = new LuaApplicationMasterParameters(getConf(),
            ImmutableMap.<String, Object>of("MASTER_HOSTNAME", hostname, "MASTER_PORT", socket.getLocalPort()));
    appMasterParams.setTrackingUrl(String.format("%s:%d", hostname, socket.getLocalPort()));
    ApplicationMasterService appMasterService = new ApplicationMasterServiceImpl(appMasterParams, getConf());
    LOG.info("Starting application master service");
    appMasterService.startAndWait();

    TaskMaster taskMaster = new TaskMaster(numVassals, initialTasks, globalState);
    LordHandler lordHandler = new LordHandler(taskMaster);
    TServerSocket serverTransport = new TServerSocket(socket);
    Lord.Processor lordProc = new Lord.Processor(lordHandler);
    final TServer thriftServer = new TThreadPoolServer(
            new TThreadPoolServer.Args(serverTransport).processor(lordProc));

    LOG.info("Starting lord thrift server");
    Thread thriftServerThread = new Thread("Lord Thrift Server") {
        @Override
        public void run() {
            thriftServer.serve();
        };
    };
    thriftServerThread.start();

    do {
        Thread.sleep(1000);
    } while (appMasterService.hasRunningContainers());

    // Send final notifications
    lordHandler.signalJobFinished();
    while (!lordHandler.finishedNotificationSent()) {
        Thread.sleep(1000);
    }
    thriftServerThread.join(1000);

    LOG.info("Stopping application master service");
    appMasterService.stopAndWait();
    return 0;
}

From source file:com.kixeye.janus.client.http.rest.DefaultRestHttpClientTest.java

@Before
public void setUp() throws Exception {
    ConfigurationManager.getConfigInstance().setProperty("janus.errorThresholdPerSec", 3);
    ConfigurationManager.getConfigInstance().setProperty("janus.shortCircuitDuration", 1000);
    ConfigurationManager.getConfigInstance().setProperty("janus.refreshIntervalInMillis", 500);

    Server server = new ContainerServer(forwardingServerContainer);
    server1Connection = new SocketConnection(server);

    ServerSocket socketServer = new ServerSocket(0);
    server1Port = socketServer.getLocalPort();
    socketServer.close();/* w  ww .  j ava  2s. c  om*/

    server1Connection.connect(new InetSocketAddress(server1Port));

    server = new ContainerServer(forwardingServerContainer);
    server2Connection = new SocketConnection(server);

    socketServer = new ServerSocket(0);
    server2Port = socketServer.getLocalPort();
    socketServer.close();

    server2Connection.connect(new InetSocketAddress(server2Port));
}

From source file:de.devbliss.apitester.dummyserver.DummyApiServer.java

private int findFreePort() {
    int port = MIN_PORT;
    for (; port < MAX_PORT; port++) {
        try {/*from   w w w.j  a  v a2  s  .  co  m*/
            new ServerSocket(port).close();
            // it was free, use it
            break;
        } catch (IOException e) {
            // so what?
        }
    }
    return port;
}

From source file:it.crs4.pydoop.mapreduce.pipes.Application.java

/**
 * Start the child process to handle the task for us.
 * @throws IOException//from   w  w w.j  av a 2s  . c  om
 * @throws InterruptedException
 */
Application(TaskInputOutputContext<K1, V1, K2, V2> context, DummyRecordReader input)
        throws IOException, InterruptedException {

    Configuration conf = context.getConfiguration();
    serverSocket = new ServerSocket(0);
    Map<String, String> env = new HashMap<String, String>();
    // add TMPDIR environment variable with the value of java.io.tmpdir
    env.put("TMPDIR", System.getProperty("java.io.tmpdir"));
    env.put(Submitter.PORT, Integer.toString(serverSocket.getLocalPort()));

    //Add token to the environment if security is enabled
    Token<JobTokenIdentifier> jobToken = TokenCache.getJobToken(context.getCredentials());
    // This password is used as shared secret key between this application and
    // child pipes process
    byte[] password = jobToken.getPassword();
    String localPasswordFile = new File(".") + Path.SEPARATOR + "jobTokenPassword";
    writePasswordToLocalFile(localPasswordFile, password, conf);
    // FIXME why is this not Submitter.SECRET_LOCATION ?
    env.put("hadoop.pipes.shared.secret.location", localPasswordFile);

    List<String> cmd = new ArrayList<String>();
    String interpretor = conf.get(Submitter.INTERPRETOR);
    if (interpretor != null) {
        cmd.add(interpretor);
    }
    String executable = context.getLocalCacheFiles()[0].toString();
    if (!(new File(executable).canExecute())) {
        // LinuxTaskController sets +x permissions on all distcache files already.
        // In case of DefaultTaskController, set permissions here.
        FileUtil.chmod(executable, "u+x");
    }
    cmd.add(executable);
    // wrap the command in a stdout/stderr capture
    // we are starting map/reduce task of the pipes job. this is not a cleanup
    // attempt. 
    TaskAttemptID taskid = context.getTaskAttemptID();

    File stdout = TaskLog.getTaskLogFile(taskid, false, TaskLog.LogName.STDOUT);
    File stderr = TaskLog.getTaskLogFile(taskid, false, TaskLog.LogName.STDERR);
    long logLength = TaskLog.getTaskLogLength(conf);
    cmd = TaskLog.captureOutAndError(null, cmd, stdout, stderr, logLength, false);
    process = runClient(cmd, env);
    clientSocket = serverSocket.accept();

    String challenge = getSecurityChallenge();
    String digestToSend = createDigest(password, challenge);
    String digestExpected = createDigest(password, digestToSend);

    handler = new OutputHandler<K2, V2>(context, input, digestExpected);
    K2 outputKey = (K2) ReflectionUtils.newInstance(context.getOutputKeyClass(), conf);
    V2 outputValue = (V2) ReflectionUtils.newInstance(context.getOutputValueClass(), conf);
    downlink = new BinaryProtocol<K1, V1, K2, V2>(clientSocket, handler, outputKey, outputValue, conf);

    downlink.authenticate(digestToSend, challenge);
    waitForAuthentication();
    LOG.debug("Authentication succeeded");
    downlink.start();
    downlink.setJobConf(conf);
}

From source file:at.sti2.sparkwave.ServerSocketThread.java

/**
 * TCP/IP Sparkwave Network Server/*  w  ww .jav a  2 s .c o m*/
 */
public void run() {

    try {

        //Open TCP/IP Server socket
        ServerSocket server = new ServerSocket(configuration.getPort());
        logger.info("Server: " + server);

        while (!Thread.interrupted()) {
            logger.info("Waiting for connection...");
            Socket sock = server.accept();
            logger.info("Connected: " + sock);

            //TODO Not every connection should cause a rebuild of the plugin chain. Should work with arbitrary many connections and failure resistent. re-use plugin threads and parser threads.

            InputStream socketStreamIn = sock.getInputStream();

            // PreProcessing Plugins to be loaded
            if (configuration.getPPPluginsConfig().size() == 2) {

                //TODO support arbitrary many plugins

                // Wiring: socketStreamIn --> (Plugin1) --> PipeOut1 --> PipeIn1
                final PipedOutputStream pipeOut1 = new PipedOutputStream();
                final PipedInputStream pipeIn1 = new PipedInputStream(pipeOut1);

                // Wiring: PipeIn1 --> (Plugin2) --> PipeOut2 --> PipeIn2
                final PipedOutputStream pipeOut2 = new PipedOutputStream();
                final PipedInputStream pipeIn2 = new PipedInputStream(pipeOut2);

                final ByteArrayOutputStream baos = new ByteArrayOutputStream();

                // plugin configuration
                PPPluginConfig pluginConfig1 = configuration.getPPPluginsConfig().get(0);
                PreProcess plugin1 = instantiateAndConfigurePlugin(pluginConfig1, socketStreamIn, pipeOut1);

                PPPluginConfig pluginConfig2 = configuration.getPPPluginsConfig().get(1);
                PreProcess plugin2 = instantiateAndConfigurePlugin(pluginConfig2, pipeIn1, pipeOut2);

                // N3 Parser
                StreamParserThread sparkStreamParserThread = new StreamParserThread(pipeIn2, queues);

                // kick-off pre-process
                sparkwaveParserExecutor.execute(plugin1);
                sparkwaveParserExecutor.execute(plugin2);

                // kick-off parser
                sparkwaveParserExecutor.execute(sparkStreamParserThread);

            } else {

                StreamParserThread sparkStreamParserThread = new StreamParserThread(socketStreamIn, queues);

                // kick-off parser
                sparkwaveParserExecutor.execute(sparkStreamParserThread);

            }

        }

    } catch (Exception e) {
        logger.error(e.getMessage());
    } finally {

    }
}

From source file:cnxchecker.Server.java

public void doit() {
    try {/* w  w  w  .  j av  a2  s  . c o m*/
        ServerSocket ss = new ServerSocket(port);
        System.out.println("[INFO] Listenning on " + ss);
        while (true) {
            try {
                Socket s = ss.accept();
                Thread handler = new ClientHandler(s);
                handler.start();
            } catch (IOException e) {
                printAndExit("Failed to accept a new client: " + e.getMessage());
            }
        }
    } catch (IOException e) {
        printAndExit("Failed to bind to " + port + ": " + e.getMessage());
    }
}

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

/**
 * This method is the constructor./* ww  w.  j  a  v a  2 s  . c o m*/
 * @param job
 *        contains BSPJob configuration
 * @param communicator
 *        the communicator between different work node
 */
public Application(BSPJob job, Communicator communicator) 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()));
    List<String> cmd = new ArrayList<String>();
    String executable = job.getJobExe();
    FileUtil.chmod(executable, "a+x");
    cmd.add(executable);
    process = runClient(cmd, env);
    clientSocket = serverSocket.accept();
    this.handler = new TaskHandler(communicator);
    this.downlink = new BinaryProtocol(clientSocket, handler);
    this.downlink.start();
}

From source file:io.reappt.adapters.kafka.KafkaAdapter.java

/**
 * Hacky way of telling cloudfoundry that the application is alive. There doesn't
 * appear to be a way of specifying --no-route to the maven plugin.
 *//*from w ww  .jav a  2s . c o  m*/
private void listen() throws IOException {
    try {
        int port = Integer.parseInt(System.getenv("PORT"));
        livenessSocket = new ServerSocket(port);
        livenessSocket.accept();
    } catch (NumberFormatException nfe) {
        // No port so don't listen
    }
}

From source file:com.mtgi.analytics.test.AbstractPerformanceTestCase.java

protected void testPerformance(TestCase basisJob, TestCase testJob) throws Throwable {

    //cache serialized form to save time on repeated test iterations
    byte[] controlData = serializeJob(new TestProcess(testThreads, testLoop, basisJob));
    byte[] testData = serializeJob(new TestProcess(testThreads, testLoop, testJob));
    StatisticsMBean controlStats = new StatisticsMBean();
    controlStats.setUnits("nanoseconds");
    StatisticsMBean testStats = new StatisticsMBean();
    testStats.setUnits("nanoseconds");

    ServerSocket listener = new ServerSocket(0);
    try {/*from   w ww.  ja  v  a 2  s  .  c  o  m*/
        int port = listener.getLocalPort();

        ProcessBuilder pb = new ProcessBuilder(System.getProperty("java.home") + separator + "/bin/java",
                "-server", "-cp", System.getProperty("java.class.path"), TestProcess.class.getName(),
                String.valueOf(port));
        pb.redirectErrorStream(false);

        //run several iterations of the test, alternating between instrumented and not
        //to absorb the affects of garbage collection.
        for (int i = 0; i < TEST_ITERATIONS; ++i) {
            System.out.println("iteration " + i);
            //switch the order of test / control runs during iteration to reduce any
            //bias that order might cause
            if (i % 2 == 0) {
                runTest(listener, pb, testStats, testData);
                runTest(listener, pb, controlStats, controlData);
            } else {
                runTest(listener, pb, controlStats, controlData);
                runTest(listener, pb, testStats, testData);
            }
            assertEquals("basis and test have same sample size after iteration " + i, controlStats.getCount(),
                    testStats.getCount());
        }
    } finally {
        listener.close();
    }

    double basisNanos = controlStats.getAverageTime();
    double cpuCoefficient = basisNanos / (double) expectedBasis;

    double expectedAverage = cpuCoefficient * averageOverhead;
    double expectedMax = cpuCoefficient * maxOverhead;

    System.out.println("control:\n" + controlStats);
    System.out.println("test:\n" + testStats);
    System.out.println("CPU Coefficient: " + cpuCoefficient);
    System.out.println("basisNanos: " + basisNanos);

    //compute the overhead as the difference between instrumented and uninstrumented
    //runs.  we want the per-event overhead to be less than .5 ms.
    double delta = testStats.getAverageTime() - basisNanos;
    //deltaWorst, my favorite sausage.  mmmmmm, dellltttaaaWwwwooorrsstt.
    double deltaWorst = testStats.getMaxTime() - controlStats.getMaxTime();

    System.out.println("Maximum expected average overhead: " + expectedAverage);
    System.out.println("Average overhead: " + delta);
    System.out.println("Maximum expected worst case overhead: " + expectedMax);
    System.out.println("Worst case overhead: " + deltaWorst);

    assertTrue("Average overhead per method cannot exceed " + expectedAverage + "ns [ " + delta + " ]",
            delta <= expectedAverage);

    assertTrue("Worst case per method overhead cannot exceed " + expectedMax + "ns [ " + deltaWorst + " ]",
            deltaWorst <= expectedMax);
}