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.rjfun.cordova.httpd.NanoHTTPD.java

/**
 * Starts a HTTP server to given port.<p>
 * Throws an IOException if the socket is already in use
 *///from  ww  w .  ja v a  2 s  .c  o  m
public NanoHTTPD(int port, AndroidFile wwwroot) throws IOException {
    myTcpPort = port;
    this.myRootDir = wwwroot;
    myServerSocket = new ServerSocket(myTcpPort);
    myThread = new Thread(new Runnable() {
        public void run() {
            try {
                while (true)
                    new HTTPSession(myServerSocket.accept());
            } catch (IOException ioe) {
            }
        }
    });
    myThread.setDaemon(true);
    myThread.start();
}

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

/**
 * This method is the constructor.//from   w  w  w  .j  a  va  2s. c  om
 * @param job
 *        contains BSPJob configuration
 * @param staff
 *        the java compute process
 * @param workerAgent
 *        Protocol that staff child process uses to contact its parent process
 */
public Application(BSPJob job, Staff staff, WorkerAgentProtocol workerAgent)
        throws IOException, InterruptedException {
    serverSocket = new ServerSocket(0);
    Map<String, String> env = new HashMap<String, String>();
    env.put("TMPDIR", System.getProperty("java.io.tmpdir"));
    LOG.info("Application: System.getProterty: " + System.getProperty("java.io.tmpdir"));
    env.put("bcbsp.pipes.command.port", Integer.toString(serverSocket.getLocalPort()));
    env.put("staffID", staff.getStaffID().toString());
    LOG.info("staffID is :" + staff.getStaffID().toString());
    List<String> cmd = new ArrayList<String>();
    String executable = staff.getJobExeLocalPath();
    FileUtil.chmod(executable, "a+x");
    cmd.add(executable);
    process = runClient(cmd, env);
    LOG.info("waiting for connect cpp process ");
    clientSocket = serverSocket.accept();
    LOG.info("=========run C++ ======");
    this.handler = new TaskHandler(job, staff, workerAgent);
    this.downlink = new BinaryProtocol(clientSocket, handler);
    this.downlink.start();
}

From source file:com.ngdata.hbaseindexer.impl.IndexerModelImplTest.java

public static int getFreePort() {
    ServerSocket socket = null;//from  w  w  w. j  av  a 2  s  . c  o m
    try {
        socket = new ServerSocket(0);
        return socket.getLocalPort();
    } catch (IOException e) {
        throw new RuntimeException("Error finding a free port", e);
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException("Error closing ServerSocket used to detect a free port.", e);
            }
        }
    }
}

From source file:org.apache.ambari.server.api.rest.KdcServerConnectionVerificationTest.java

private static void createSocketServer(int port) throws Exception {
    serverSocket = new ServerSocket(port);
    new SocketThread().start();
}

From source file:voldemort.ServerTestUtils.java

/**
 * Return an array of free ports as chosen by new ServerSocket(0)
 * /*from  ww w  .  j  a v a2  s  .co m*/
 * There is no guarantee that the ports returned will be free when the
 * caller attempts to bind to some returned port. This is a
 * time-of-check-to-time-of-use (TOCTOU) issue that cannot be avoided.
 */
public static int[] findFreePorts(int n) {
    logger.info(
            "findFreePorts cannot guarantee that ports identified as free will still be free when used. This is effectively a TOCTOU issue. Expect intermittent BindException when \"free\" ports are used.");
    int[] ports = new int[n];
    ServerSocket[] sockets = new ServerSocket[n];
    try {
        for (int i = 0; i < n; i++) {
            sockets[i] = new ServerSocket(0);
            ports[i] = sockets[i].getLocalPort();
        }
        return ports;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        for (int i = 0; i < n; i++) {
            try {
                if (sockets[i] != null)
                    sockets[i].close();
            } catch (IOException e) {
            }
        }
    }
}

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 . j a  v  a  2 s.  c o  m*/

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

    // TODO: need an acknowledgement?

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

    return sb.toString();
}

From source file:net.mybox.mybox.Common.java

/**
 * Checks to see if a specific port is available.
 *
 * @param port the port to check for availability
 *///from ww w. jav  a 2 s .c  o  m
public static boolean portAvailable(int port) {
    if (port < 0 || port > 65535) {
        throw new IllegalArgumentException("Invalid start port: " + port);
    }

    ServerSocket ss = null;
    DatagramSocket ds = null;
    try {
        ss = new ServerSocket(port);
        ss.setReuseAddress(true);
        ds = new DatagramSocket(port);
        ds.setReuseAddress(true);
        return true;
    } catch (IOException e) {
    } finally {
        if (ds != null) {
            ds.close();
        }

        if (ss != null) {
            try {
                ss.close();
            } catch (IOException e) {
                /* should not be thrown */
            }
        }
    }

    return false;
}

From source file:com.endpoint.lg.browser.service.BrowserInstance.java

/**
 * Finds an available debug port/*from   ww w.  j a v a 2 s .c  o m*/
 *
 * This could fail, if we find a port and something steals it before we get
 * a browser listening on it. This seems unlikely. Note that chromium
 * doesn't fail if its assigned debug port is unavailable (at least so far
 * as I can tell)
 */
private int findDebugPort() {
    int debugPort = 0;
    ServerSocket s = null;

    for (int i = MIN_DEBUG_PORT; i < MAX_DEBUG_PORT; i++) {
        try {
            s = new ServerSocket(i);
            s.setReuseAddress(true);
            debugPort = i;
        } catch (IOException e) {
            // Port isn't available
            getLog().debug("Port " + i + " isn't available");
        } finally {
            try {
                if (s != null) {
                    s.close();
                }
            } catch (IOException e) {
                // s wasn't opened. Don't throw this
            }
        }
        if (debugPort != 0)
            break;
    }
    if (debugPort == 0) {
        getLog().error("Couldn't find unused debug port for new browser activity");
        return 0;
    }
    getLog().debug("Found debug port " + debugPort + " for new browser instance");
    return debugPort;
}

From source file:org.apache.servicemix.http.ProviderEndpointTest.java

public void testSendProblemWithServerDying() throws Exception {
    HttpComponent http = new HttpComponent();

    HttpSoapProviderEndpoint ep1 = new HttpSoapProviderEndpoint();
    ep1.setService(new QName("http://servicemix.apache.org/samples/wsdl-first", "PersonService"));
    ep1.setEndpoint("soap");
    ep1.setWsdl(new ClassPathResource("person.wsdl"));
    ep1.setValidateWsdl(false); // TODO: Soap 1.2 not handled yet
    ep1.setUseJbiWrapper(true);/*w  ww.  ja  v a 2  s. co m*/

    http.addEndpoint(ep1);
    container.activateComponent(http, "http");

    container.start();

    new Thread() {
        public void run() {
            ServerSocket ss = null;
            try {
                ss = new ServerSocket(8192);
                Socket s = ss.accept();
                Thread.sleep(50);
                s.close();
            } catch (Throwable t) {
                t.printStackTrace();
            } finally {
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }.start();

    ServiceMixClient client = new DefaultServiceMixClient(container);
    InOut me = client.createInOutExchange();
    me.setService(new QName("http://servicemix.apache.org/samples/wsdl-first", "PersonService"));
    me.setOperation(new QName("http://servicemix.apache.org/samples/wsdl-first", "GetPerson"));
    me.getInMessage().setContent(
            new StringSource("<jbi:message xmlns:jbi=\"http://java.sun.com/xml/ns/jbi/wsdl-11-wrapper\""
                    + "             xmlns:msg=\"http://servicemix.apache.org/samples/wsdl-first/types\" "
                    + "             name=\"Hello\" " + "             type=\"msg:HelloRequest\" "
                    + "             version=\"1.0\">" + "  <jbi:part>"
                    + "    <msg:GetPerson><msg:personId>id</msg:personId></msg:GetPerson>" + "  </jbi:part>"
                    + "</jbi:message>"));
    client.sendSync(me);
    assertEquals(ExchangeStatus.ERROR, me.getStatus());
}

From source file:com.evolveum.midpoint.repo.sql.SqlRepositoryFactory.java

private void checkPort(int port) throws RepositoryServiceFactoryException {
    if (port >= 65635 || port < 0) {
        throw new RepositoryServiceFactoryException("Port must be in range 0-65634, not '" + port + "'.");
    }//from www .j av a2s.c o m

    ServerSocket ss = null;
    try {
        ss = new ServerSocket(port);
        ss.setReuseAddress(true);
    } catch (BindException e) {
        throw new RepositoryServiceFactoryException("Configured port (" + port + ") for H2 already in use.", e);
    } catch (IOException e) {
        LOGGER.error("Reported IO error, while binding ServerSocket to port " + port
                + " used to test availability " + "of port for H2 Server", e);
    } finally {
        try {
            if (ss != null) {
                ss.close();
            }
        } catch (IOException ex) {
            LOGGER.error("Reported IO error, while closing ServerSocket used to test availability "
                    + "of port for H2 Server", ex);
        }
    }
}