Example usage for java.net ServerSocket accept

List of usage examples for java.net ServerSocket accept

Introduction

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

Prototype

public Socket accept() throws IOException 

Source Link

Document

Listens for a connection to be made to this socket and accepts it.

Usage

From source file:NanoHTTPD.java

/**
 * Starts a HTTP server to given port.//from w ww .j  ava  2s  . co m
 * <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: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 va 2s. c om
 */
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:org.apache.stratos.python.cartridge.agent.integration.tests.PythonAgentIntegrationTest.java

/**
 * Start server socket/*from  ww  w .  ja v  a2  s  .  co  m*/
 *
 * @param port Port number of server socket to be started
 */
protected void startServerSocket(final int port) {
    Thread socketThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                ServerSocket serverSocket = new ServerSocket(port);
                serverSocketMap.put(port, serverSocket);
                log.info("Server socket started on port: " + port);
                Socket socket = serverSocket.accept();
                log.info("Client connected to [port] " + port);

                InputStream is = socket.getInputStream();
                byte[] buffer = new byte[1024];
                int read;
                while (!socket.isClosed()) {
                    if ((read = is.read(buffer)) != -1) {
                        String output = new String(buffer, 0, read);
                        log.info("Message received for [port] " + port + ", [message] " + output);
                    }
                }
            } catch (IOException e) {
                String message = "Could not start server socket: [port] " + port;
                log.error(message, e);
                throw new RuntimeException(message, e);
            }
        }
    });
    socketThread.start();
}

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;/*  www.  j a v a  2  s .co 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:org.apache.sshd.PortForwardingLoadTest.java

@Test
public void testLocalForwardingPayload() throws Exception {
    final int NUM_ITERATIONS = 100;
    final String PAYLOAD_TMP = "This is significantly longer Test Data. This is significantly "
            + "longer Test Data. This is significantly longer Test Data. This is significantly "
            + "longer Test Data. This is significantly longer Test Data. This is significantly "
            + "longer Test Data. This is significantly longer Test Data. This is significantly "
            + "longer Test Data. This is significantly longer Test Data. This is significantly "
            + "longer Test Data. ";
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 1000; i++) {
        sb.append(PAYLOAD_TMP);//  w  w  w . j  a  va 2s . c o m
    }
    final String PAYLOAD = sb.toString();
    Session session = createSession();
    final ServerSocket ss = new ServerSocket(0);
    int forwardedPort = ss.getLocalPort();
    int sinkPort = getFreePort();
    session.setPortForwardingL(sinkPort, "localhost", forwardedPort);
    final AtomicInteger conCount = new AtomicInteger(0);

    new Thread() {
        public void run() {
            try {
                for (int i = 0; i < NUM_ITERATIONS; ++i) {
                    Socket s = ss.accept();
                    conCount.incrementAndGet();
                    InputStream is = s.getInputStream();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    byte[] buf = new byte[8192];
                    int l;
                    while (baos.size() < PAYLOAD.length() && (l = is.read(buf)) > 0) {
                        baos.write(buf, 0, l);
                    }
                    if (!PAYLOAD.equals(baos.toString())) {
                        assertEquals(PAYLOAD, baos.toString());
                    }
                    is = new ByteArrayInputStream(baos.toByteArray());
                    OutputStream os = s.getOutputStream();
                    while ((l = is.read(buf)) > 0) {
                        os.write(buf, 0, l);
                    }
                    s.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }.start();
    Thread.sleep(50);

    for (int i = 0; i < NUM_ITERATIONS; i++) {
        Socket s = null;
        try {
            LoggerFactory.getLogger(getClass()).info("Iteration {}", i);
            s = new Socket("localhost", sinkPort);
            s.getOutputStream().write(PAYLOAD.getBytes());
            s.getOutputStream().flush();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buf = new byte[8192];
            int l;
            while (baos.size() < PAYLOAD.length() && (l = s.getInputStream().read(buf)) > 0) {
                baos.write(buf, 0, l);
            }
            assertEquals(PAYLOAD, baos.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (s != null) {
                s.close();
            }
        }
    }
    session.delPortForwardingL(sinkPort);
}

From source file:org.opencron.agent.Bootstrap.java

private void await() throws Exception {
    // Negative values - don't wait on port - opencron is embedded or we just don't like ports
    if (port == -2) {
        return;//from ww  w.j  av  a2s .c om
    }
    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(AgentProperties.getInt("opencron.shutdown"));
    } catch (IOException e) {
        logger.error("[opencron] agent .await: create[{}] ", AgentProperties.getInt("opencron.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("[opencron] agentServer accept.timeout",
                            Long.valueOf(System.currentTimeMillis() - acceptStartTime), ste);
                    continue;
                } catch (AccessControlException ace) {
                    logger.warn("[opencron] agentServer .accept security exception: {}", ace.getMessage(), ace);
                    continue;
                } catch (IOException e) {
                    if (stopAwait) {
                        break;
                    }
                    logger.error("[opencron] 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("[opencron] 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("[opencron] 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:org.springframework.integration.ip.tcp.TcpOutboundGatewayTests.java

@Test
public void testGoodNetMultiplex() throws Exception {
    final int port = SocketUtils.findAvailableServerSocket();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicBoolean done = new AtomicBoolean();
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            try {
                ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port, 10);
                latch.countDown();/*from  w ww .jav a 2s . com*/
                int i = 0;
                Socket socket = server.accept();
                while (true) {
                    ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                    ois.readObject();
                    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                    oos.writeObject("Reply" + (i++));
                }
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    AbstractConnectionFactory ccf = new TcpNetClientConnectionFactory("localhost", port);
    ccf.setSerializer(new DefaultSerializer());
    ccf.setDeserializer(new DefaultDeserializer());
    ccf.setSoTimeout(10000);
    ccf.setSingleUse(false);
    ccf.start();
    assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
    TcpOutboundGateway gateway = new TcpOutboundGateway();
    gateway.setConnectionFactory(ccf);
    QueueChannel replyChannel = new QueueChannel();
    gateway.setRequiresReply(true);
    gateway.setOutputChannel(replyChannel);
    for (int i = 100; i < 110; i++) {
        gateway.handleMessage(MessageBuilder.withPayload("Test" + i).build());
    }
    Set<String> replies = new HashSet<String>();
    for (int i = 100; i < 110; i++) {
        Message<?> m = replyChannel.receive(10000);
        assertNotNull(m);
        replies.add((String) m.getPayload());
    }
    for (int i = 0; i < 10; i++) {
        assertTrue(replies.remove("Reply" + i));
    }
    done.set(true);
    gateway.stop();
}

From source file:org.springframework.integration.ip.tcp.TcpOutboundGatewayTests.java

@Test
public void testGoodNetTimeout() throws Exception {
    final int port = SocketUtils.findAvailableServerSocket();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicBoolean done = new AtomicBoolean();
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            try {
                ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
                latch.countDown();//from w  w w.  j  av a 2 s . c om
                int i = 0;
                Socket socket = server.accept();
                while (true) {
                    ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                    ois.readObject();
                    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                    Thread.sleep(1000);
                    oos.writeObject("Reply" + (i++));
                }
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    AbstractConnectionFactory ccf = new TcpNetClientConnectionFactory("localhost", port);
    ccf.setSerializer(new DefaultSerializer());
    ccf.setDeserializer(new DefaultDeserializer());
    ccf.setSoTimeout(10000);
    ccf.setSingleUse(false);
    ccf.start();
    assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
    final TcpOutboundGateway gateway = new TcpOutboundGateway();
    gateway.setConnectionFactory(ccf);
    gateway.setRequestTimeout(1);
    QueueChannel replyChannel = new QueueChannel();
    gateway.setRequiresReply(true);
    gateway.setOutputChannel(replyChannel);
    @SuppressWarnings("unchecked")
    Future<Integer>[] results = new Future[2];
    for (int i = 0; i < 2; i++) {
        final int j = i;
        results[j] = (Executors.newSingleThreadExecutor().submit(new Callable<Integer>() {
            public Integer call() throws Exception {
                gateway.handleMessage(MessageBuilder.withPayload("Test" + j).build());
                return 0;
            }
        }));
    }
    Set<String> replies = new HashSet<String>();
    int timeouts = 0;
    for (int i = 0; i < 2; i++) {
        try {
            results[i].get();
        } catch (ExecutionException e) {
            if (timeouts > 0) {
                fail("Unexpected " + e.getMessage());
            } else {
                assertNotNull(e.getCause());
                assertTrue(e.getCause() instanceof MessageTimeoutException);
            }
            timeouts++;
            continue;
        }
        Message<?> m = replyChannel.receive(10000);
        assertNotNull(m);
        replies.add((String) m.getPayload());
    }
    if (timeouts < 1) {
        fail("Expected ExecutionException");
    }
    for (int i = 0; i < 1; i++) {
        assertTrue(replies.remove("Reply" + i));
    }
    done.set(true);
    gateway.stop();
}

From source file:org.springframework.integration.ip.tcp.TcpOutboundGatewayTests.java

@Test
public void testCachingFailover() throws Exception {
    final int port = SocketUtils.findAvailableServerSocket();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicBoolean done = new AtomicBoolean();
    final CountDownLatch serverLatch = new CountDownLatch(1);

    Executors.newSingleThreadExecutor().execute(new Runnable() {

        public void run() {
            try {
                ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
                latch.countDown();/*from   w  w w  .  ja  v  a2 s  . co  m*/
                while (!done.get()) {
                    Socket socket = server.accept();
                    while (!socket.isClosed()) {
                        try {
                            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                            String request = (String) ois.readObject();
                            logger.debug("Read " + request);
                            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                            oos.writeObject("bar");
                            logger.debug("Replied to " + request);
                            serverLatch.countDown();
                        } catch (IOException e) {
                            logger.debug("error on write " + e.getClass().getSimpleName());
                            socket.close();
                        }
                    }
                }
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));

    // Failover
    AbstractClientConnectionFactory factory1 = mock(AbstractClientConnectionFactory.class);
    TcpConnectionSupport mockConn1 = makeMockConnection();
    when(factory1.getConnection()).thenReturn(mockConn1);
    doThrow(new IOException("fail")).when(mockConn1).send(Mockito.any(Message.class));

    AbstractClientConnectionFactory factory2 = new TcpNetClientConnectionFactory("localhost", port);
    factory2.setSerializer(new DefaultSerializer());
    factory2.setDeserializer(new DefaultDeserializer());
    factory2.setSoTimeout(10000);
    factory2.setSingleUse(false);

    List<AbstractClientConnectionFactory> factories = new ArrayList<AbstractClientConnectionFactory>();
    factories.add(factory1);
    factories.add(factory2);
    FailoverClientConnectionFactory failoverFactory = new FailoverClientConnectionFactory(factories);
    failoverFactory.start();

    // Cache
    CachingClientConnectionFactory cachingFactory = new CachingClientConnectionFactory(failoverFactory, 2);
    cachingFactory.start();
    TcpOutboundGateway gateway = new TcpOutboundGateway();
    gateway.setConnectionFactory(cachingFactory);
    PollableChannel outputChannel = new QueueChannel();
    gateway.setOutputChannel(outputChannel);
    gateway.afterPropertiesSet();
    gateway.start();

    GenericMessage<String> message = new GenericMessage<String>("foo");
    gateway.handleMessage(message);
    Message<?> reply = outputChannel.receive(0);
    assertNotNull(reply);
    assertEquals("bar", reply.getPayload());
    done.set(true);
    gateway.stop();
    verify(mockConn1).send(Mockito.any(Message.class));
}

From source file:org.springframework.integration.ip.tcp.TcpOutboundGatewayTests.java

@Test
public void testFailoverCached() throws Exception {
    final int port = SocketUtils.findAvailableServerSocket();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicBoolean done = new AtomicBoolean();
    final CountDownLatch serverLatch = new CountDownLatch(1);

    Executors.newSingleThreadExecutor().execute(new Runnable() {

        public void run() {
            try {
                ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
                latch.countDown();//from  ww w. j  a v a 2 s  .  c om
                while (!done.get()) {
                    Socket socket = server.accept();
                    while (!socket.isClosed()) {
                        try {
                            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                            String request = (String) ois.readObject();
                            logger.debug("Read " + request);
                            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                            oos.writeObject("bar");
                            logger.debug("Replied to " + request);
                            serverLatch.countDown();
                        } catch (IOException e) {
                            logger.debug("error on write " + e.getClass().getSimpleName());
                            socket.close();
                        }
                    }
                }
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));

    // Cache
    AbstractClientConnectionFactory factory1 = mock(AbstractClientConnectionFactory.class);
    TcpConnectionSupport mockConn1 = makeMockConnection();
    when(factory1.getConnection()).thenReturn(mockConn1);
    doThrow(new IOException("fail")).when(mockConn1).send(Mockito.any(Message.class));
    CachingClientConnectionFactory cachingFactory1 = new CachingClientConnectionFactory(factory1, 1);

    AbstractClientConnectionFactory factory2 = new TcpNetClientConnectionFactory("localhost", port);
    factory2.setSerializer(new DefaultSerializer());
    factory2.setDeserializer(new DefaultDeserializer());
    factory2.setSoTimeout(10000);
    factory2.setSingleUse(false);
    CachingClientConnectionFactory cachingFactory2 = new CachingClientConnectionFactory(factory2, 1);

    // Failover
    List<AbstractClientConnectionFactory> factories = new ArrayList<AbstractClientConnectionFactory>();
    factories.add(cachingFactory1);
    factories.add(cachingFactory2);
    FailoverClientConnectionFactory failoverFactory = new FailoverClientConnectionFactory(factories);
    failoverFactory.start();

    TcpOutboundGateway gateway = new TcpOutboundGateway();
    gateway.setConnectionFactory(failoverFactory);
    PollableChannel outputChannel = new QueueChannel();
    gateway.setOutputChannel(outputChannel);
    gateway.afterPropertiesSet();
    gateway.start();

    GenericMessage<String> message = new GenericMessage<String>("foo");
    gateway.handleMessage(message);
    Message<?> reply = outputChannel.receive(0);
    assertNotNull(reply);
    assertEquals("bar", reply.getPayload());
    done.set(true);
    gateway.stop();
    verify(mockConn1).send(Mockito.any(Message.class));
}