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:NanoHTTPD.java

/**
 * Starts a HTTP server to given port.//  w w w. j a  v a2  s. c  om
 * <p>
 * Throws an IOException if the socket is already in use
 */
public NanoHTTPD(int port) throws IOException {
    myTcpPort = port;

    final ServerSocket ss = new ServerSocket(myTcpPort);
    Thread t = new Thread(new Runnable() {
        public void run() {
            try {
                while (true)
                    new HTTPSession(ss.accept());
            } catch (IOException ioe) {
            }
        }
    });
    t.setDaemon(true);
    t.start();
}

From source file:lockstep.LockstepServer.java

/**
 * This method puts the server in waiting for client connections. It returns
 * when the expected number of clients have successfully completed the 
 * handshake./*from   w  w w.  j  a  v a 2 s.  c o  m*/
 * Parallel threads are started to handle the handshakes.
 * In case of failure, all threads are interrupted and then the exception is
 * propagated.
 * 
 * @throws IOException In case of failure on opening the ServerSocket and 
 * accepting connections through it 
 * @throws InterruptedException In case of failure during the handshake 
 * sessions
 */
private void handshakePhase() throws IOException, InterruptedException {
    ServerSocket tcpServerSocket = new ServerSocket(tcpPort);

    CyclicBarrier barrier = new CyclicBarrier(this.clientsNumber);
    CountDownLatch latch = new CountDownLatch(this.clientsNumber);

    //Each session of the protocol starts with a different random frame number
    int firstFrameNumber = (new Random()).nextInt(1000) + 100;

    Thread[] handshakeSessions = new Thread[clientsNumber];

    for (int i = 0; i < clientsNumber; i++) {
        Socket tcpConnectionSocket = tcpServerSocket.accept();
        LOG.info("Connection " + i + " accepted from " + tcpConnectionSocket.getInetAddress().getHostAddress());
        handshakeSessions[i] = new Thread(
                () -> serverHandshakeProtocol(tcpConnectionSocket, firstFrameNumber, barrier, latch, this));
        handshakeSessions[i].start();
    }
    try {
        latch.await();
    } catch (InterruptedException inEx) {
        for (Thread handshakeSession : handshakeSessions)
            handshakeSession.interrupt();

        for (Thread handshakeSession : handshakeSessions)
            handshakeSession.join();

        throw new InterruptedException();
    }
    LOG.info("All handshakes completed");
}

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

/**
 * This method is the constructor./*from www. j a v  a 2 s. c om*/
 * @param conf
 *        contains Job configuration
 * @param processType
 *        the type of c++ process(for staff or workmanager)
 */
public Application(Configuration conf, String processType) 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);
    List<String> cmd = new ArrayList<String>();
    String executable = conf.get(Constants.USER_BC_BSP_JOB_EXE);
    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:net.grinder.util.NetworkUtils.java

/**
 * Check if the given port is available.
 *
 * @param inetAddress address to be bound
 * @param port        port to be checked
 * @return true if available/*from  ww w .  j a va 2  s  .com*/
 */
private static boolean checkExactPortAvailability(InetAddress inetAddress, int port) {
    ServerSocket socket = null;
    try {
        if (inetAddress == null) {
            socket = new ServerSocket(port);
        } else {
            socket = new ServerSocket(port, 1, inetAddress);
        }
        return true;
    } catch (IOException e) {
        return false;
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                // FALL THROUGH
                noOp();
            }
        }
    }
}

From source file:com.appeligo.channelfeed.CaptureApp.java

private void catchCaptions(final String captionPort) {
    Thread serverThread = new Thread("Caption Catcher") {
        @Override/*from   ww  w .ja  v  a  2s  .co m*/
        public void run() {
            try {
                int count = 0;
                ServerSocket server = new ServerSocket(Integer.parseInt(captionPort));
                while (true) {
                    try {
                        count++;
                        VBISocketReaderThread vbiSocketReaderThread = new VBISocketReaderThread(
                                "VBISocketReader " + count + "@" + captionPort, server.accept());

                        Destinations destinations = new Destinations();
                        destinations.setCaptionDocumentRoot(captionDocumentRoot);
                        destinations.setDestinationURLs(destinationURLs, destinationRaws);
                        destinations.setSendXDS(false);
                        destinations.setSendITV(false);
                        if (writing) {
                            destinations.setFileWriter(new FileWriter());
                        }

                        vbiSocketReaderThread.setEpgService(getEpgService());
                        vbiSocketReaderThread.setDestinations(destinations);

                        destinations.connect();
                        vbiSocketReaderThread.start();

                    } catch (MalformedURLException e1) {
                        log.error("Exception on a channel", e1);
                    } catch (IOException e1) {
                        log.error("Exception on a channel", e1);
                    }
                }
            } catch (IOException e1) {
                log.error("Exception with server socket", e1);
            } catch (NumberFormatException e1) {
                log.error("Bad port number: " + captionPort, e1);
                return;
            }
        }
    };
    serverThread.start();
}

From source file:com.barchart.netty.server.http.handlers.TestStaticResourceHandler.java

@Before
public void setUp() throws Exception {

    final ServerSocket s = new ServerSocket(0);
    port = s.getLocalPort();/*from ww  w  . j a  v  a2s.co  m*/
    s.close();

    server = Servers.createHttpServer().group(new NioEventLoopGroup())
            .requestHandler("/classpath", new StaticResourceHandler(this.getClass().getClassLoader(), "/files"))
            .requestHandler("/file", new StaticResourceHandler(
                    new File(System.getProperty("user.dir") + "/src/test/resources/files")));

    server.listen(port, "localhost");

    client = new DefaultHttpClient(new PoolingClientConnectionManager());

}

From source file:com.moss.appsnap.keeper.windows.MSWindowsDesktopIntegrationStrategy.java

public void startLocalApiServer(final ApiMessageHandler handler) {
    try {/*from w w  w  . ja v  a  2  s. c  o m*/
        {
            if (!snapFsLayout.portFile.exists() && !snapFsLayout.portFile.createNewFile()) {
                throw new RuntimeException("Could not create file: " + snapFsLayout.portFile.getAbsolutePath());
            }
            snapFsLayout.portFile.deleteOnExit();
            Writer w = new FileWriter(snapFsLayout.portFile);
            w.write(Integer.toString(KEEPER_LOCAL_PORT));
            w.close();
        }
        final ServerSocket server = new ServerSocket(KEEPER_LOCAL_PORT);//, 0, InetAddress.getLocalHost());

        new Thread("Local API Server Thread") {
            public void run() {
                while (true) {
                    try {
                        log.info("Waiting for local connection.");
                        Socket s = server.accept();
                        log.info("Connection established.");
                        handler.handle(new SocketMessageConnection(s));
                        log.info("Done");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

    } catch (Exception e) {
        throw new RuntimeException();
    }
}

From source file:edu.umass.cs.msocket.proxy.location.LocationService.java

/**
 * @see java.lang.Thread#run()/* w  w  w  . j  a  va2  s.co  m*/
 */
@Override
public void run() {
    while (!killed) {
        try {
            // Create the server socket
            ss = new ServerSocket(0);

            // Publish location service IP in the GNS
            final UniversalGnsClient gnsClient = gnsCredentials.getGnsClient();
            final String ipPort = locationServiceInfo.getIpAddress() + ":" + ss.getLocalPort();
            logger.info("Publishing Location service IP (" + ipPort + ") in GNS.");
            final GuidEntry guidEntry = gnsCredentials.getGuidEntry();
            gnsClient.fieldReplaceOrCreate(guidEntry.getGuid(), GnsConstants.LOCATION_SERVICE_IP,
                    new JSONArray().put(ipPort), guidEntry);
            gnsClient.aclAdd(AccessType.READ_WHITELIST, guidEntry, GnsConstants.LOCATION_SERVICE_IP, null);

            // Start the thread that collect information about proxy status
            statusThread = new ProxyStatusThread(proxyGroupName, gnsCredentials);
            statusThread.start();

            // Now accepting connections
            while (!ss.isClosed()) {
                new LocateServiceThread(ss.accept(), this).start();
            }
        } catch (Exception e) {
            logger.log(Level.WARNING, "Location service failed with error " + e, e);
        }
    }
    if (statusThread != null)
        statusThread.killIt();

    logger.log(Level.INFO, "Location service has been terminated");
}

From source file:gr.iit.demokritos.cru.cpserver.CPServer.java

public void StartCPServer() throws IOException, Exception {
    ServerSocket serversocket = new ServerSocket(port);
    System.out.println("Start CPServer");
    Bookeeper bk = new Bookeeper(this.properties);
    while (true) {
        System.out.println("Inside While");
        Socket connectionsocket = serversocket.accept();
        System.out.println("Inet");
        //InetAddress client = connectionsocket.getInetAddress();

        BufferedReader input = new BufferedReader(new InputStreamReader(connectionsocket.getInputStream()));
        DataOutputStream output = new DataOutputStream(connectionsocket.getOutputStream());

        httpHandler(input, output);//ww  w .  j ava 2  s  .  c om
    }
}

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

@Test(expected = VaultClientException.class)
public void delete_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());

    vaultClient.delete("app/api-key");
}