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:org.springframework.integration.ip.tcp.TcpOutboundGatewayTests.java

private void testGWPropagatesSocketCloseGuts(final int port, AbstractClientConnectionFactory ccf)
        throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicBoolean done = new AtomicBoolean();
    final AtomicReference<String> lastReceived = new AtomicReference<String>();
    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  2s.c o m
                int i = 0;
                while (!done.get()) {
                    Socket socket = server.accept();
                    i++;
                    while (!socket.isClosed()) {
                        try {
                            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                            String request = (String) ois.readObject();
                            logger.debug("Read " + request + " closing socket");
                            socket.close();
                            lastReceived.set(request);
                            serverLatch.countDown();
                        } catch (IOException e) {
                            socket.close();
                        }
                    }
                }
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
    final TcpOutboundGateway gateway = new TcpOutboundGateway();
    gateway.setConnectionFactory(ccf);
    gateway.setRequestTimeout(Integer.MAX_VALUE);
    QueueChannel replyChannel = new QueueChannel();
    gateway.setRequiresReply(true);
    gateway.setOutputChannel(replyChannel);
    gateway.setRemoteTimeout(5000);
    gateway.afterPropertiesSet();
    gateway.start();
    try {
        gateway.handleMessage(MessageBuilder.withPayload("Test").build());
        fail("expected failure");
    } catch (Exception e) {
        assertTrue(e.getCause() instanceof EOFException);
    }
    assertEquals(0, TestUtils.getPropertyValue(gateway, "pendingReplies", Map.class).size());
    Message<?> reply = replyChannel.receive(0);
    assertNull(reply);
    done.set(true);
    ccf.getConnection();
}

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

private void runTest(ServerSocket listener, ProcessBuilder launcher, StatisticsMBean stats, byte[] jobData)
        throws IOException, InterruptedException {
    Process proc = launcher.start();

    //connect stdout and stderr to parent process streams
    if (log.isDebugEnabled()) {
        new PipeThread(proc.getInputStream(), System.out).start();
        new PipeThread(proc.getErrorStream(), System.err).start();
    } else {//from   w ww  . java2  s.  c om
        NullOutput sink = new NullOutput();
        new PipeThread(proc.getInputStream(), sink).start();
        new PipeThread(proc.getErrorStream(), sink).start();
    }

    //wait for the incoming connection from the child process.
    Socket sock = listener.accept();
    try {
        //connection established, send the job.
        OutputStream os = sock.getOutputStream();
        os.write(jobData);
        os.flush();

        //read measurements back.
        DataInputStream dis = new DataInputStream(sock.getInputStream());
        for (long measure = dis.readLong(); measure >= 0; measure = dis.readLong())
            stats.add(measure);

        //send ack byte to tell the child proc its ok to hang up.
        os.write(1);
        os.flush();

    } finally {
        sock.close();
    }

    assertEquals("Child process ended successfully", 0, proc.waitFor());
}

From source file:org.bml.util.server.BServer.java

/**
* The runInvProxy class starts a new server socket and listens for
  * connections from clients. Upon recieving a connection, it starts a new
  * InvProxyThread to process the connection.
 * @param aPort The port to attach to//from   www.j  a v  a 2  s.  co m
 * @param aNumThreads the number of worker threads
 * @param aSleepTime sleep time in between checks
 * @param aMaxQueueLength the max requests to queue up
 * @param accessLog a Log to write access info 
 */
public void runInvProxy(int aPort, int aNumThreads, long aSleepTime, int aMaxQueueLength, Log accessLog) {
    this.accessLog = accessLog;

    if (LOG.isDebugEnabled()) {
        LOG.debug("Attempting to start server on port: " + aPort);
    }

    //Start Server
    ServerSocket myServerSocket = null;
    try {
        myServerSocket = new ServerSocket(aPort, aMaxQueueLength);
    } catch (IOException e) {
        System.out.println(e);
        return;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Server started on port: " + aPort);
    }

    //Continuously accept connections and start threads to
    //process connections.
    while (!theDone) {

        if (LOG.isDebugEnabled()) {
            LOG.debug("Ready to accept client connection");
        }

        Socket myClientSocket = null;
        try {
            myClientSocket = myServerSocket.accept();
        } catch (IOException e) {
            System.out.println("Accept Error: " + e);
            break;
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Accepted connection from client: " + myClientSocket.getInetAddress()
                    + "\nStarting thread to deal with connection");
        }

        //Make sure there aren't too many active threads
        if (aNumThreads != -1) {
            while (Thread.activeCount() > aNumThreads) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Too many active threads.  Waiting " + aSleepTime
                            + "(ms) before trying to start new HitServerInvProxyThread again");
                }
                try {
                    Thread.sleep(aSleepTime);
                } catch (InterruptedException e) {
                    System.out.println(e);
                    break;
                }
            }
        }
        if (myClientSocket != null && myClientSocket.isConnected()) {
            new InvProxyThread(this, myClientSocket, this.accessLog);
        } else {
            if (LOG.isWarnEnabled()) {
                LOG.warn("Client Socket is null or not connected when starting thread");
            }
            break;
        }
    }

    //Closing socket
    if (LOG.isDebugEnabled()) {
        LOG.debug("Closing server socket.  In general, we should never get here.");
    }

    try {
        myServerSocket.close();
    } catch (IOException e) {
        System.out.println(e);
        return;
    }
}

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

/**
 * Sends 2 concurrent messages on a shared connection. The GW single threads
 * these requests. The first will timeout; the second should receive its
 * own response, not that for the first.
 * @throws Exception/*from   w w  w  .  java  2  s .  c  om*/
 */
private void testGoodNetGWTimeoutGuts(final int port, AbstractConnectionFactory ccf)
        throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicBoolean done = new AtomicBoolean();
    /*
     * The payload of the last message received by the remote side;
     * used to verify the correct response is received.
     */
    final AtomicReference<String> lastReceived = new AtomicReference<String>();
    final CountDownLatch serverLatch = new CountDownLatch(2);

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

        public void run() {
            try {
                ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
                latch.countDown();
                int i = 0;
                while (!done.get()) {
                    Socket socket = server.accept();
                    i++;
                    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());
                            if (i < 2) {
                                Thread.sleep(1000);
                            }
                            oos.writeObject(request.replace("Test", "Reply"));
                            logger.debug("Replied to " + request);
                            lastReceived.set(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));
    final TcpOutboundGateway gateway = new TcpOutboundGateway();
    gateway.setConnectionFactory(ccf);
    gateway.setRequestTimeout(Integer.MAX_VALUE);
    QueueChannel replyChannel = new QueueChannel();
    gateway.setRequiresReply(true);
    gateway.setOutputChannel(replyChannel);
    gateway.setRemoteTimeout(500);
    @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 {
                // increase the timeout after the first send
                if (j > 0) {
                    gateway.setRemoteTimeout(5000);
                }
                gateway.handleMessage(MessageBuilder.withPayload("Test" + j).build());
                return j;
            }
        }));
        Thread.sleep(50);
    }
    // wait until the server side has processed both requests
    assertTrue(serverLatch.await(10, TimeUnit.SECONDS));
    List<String> replies = new ArrayList<String>();
    int timeouts = 0;
    for (int i = 0; i < 2; i++) {
        try {
            int result = results[i].get();
            String reply = (String) replyChannel.receive(1000).getPayload();
            logger.debug(i + " got " + result + " " + reply);
            replies.add(reply);
        } catch (ExecutionException e) {
            if (timeouts >= 2) {
                fail("Unexpected " + e.getMessage());
            } else {
                assertNotNull(e.getCause());
                assertTrue(e.getCause() instanceof MessageTimeoutException);
            }
            timeouts++;
            continue;
        }
    }
    assertEquals("Expected exactly one ExecutionException", 1, timeouts);
    assertEquals(1, replies.size());
    assertEquals(lastReceived.get().replace("Test", "Reply"), replies.get(0));
    done.set(true);
    assertEquals(0, TestUtils.getPropertyValue(gateway, "pendingReplies", Map.class).size());
    gateway.stop();
}

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.//ww w.j  av 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:org.apache.sshd.PortForwardingLoadTest.java

@Test
public void testRemoteForwardingPayload() throws Exception {
    final int NUM_ITERATIONS = 100;
    final String PAYLOAD = "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. ";
    Session session = createSession();/*  w ww.  jav  a  2 s  . c  o  m*/
    final ServerSocket ss = new ServerSocket(0);
    int forwardedPort = ss.getLocalPort();
    int sinkPort = getFreePort();
    session.setPortForwardingR(sinkPort, "localhost", forwardedPort);
    final boolean started[] = new boolean[1];
    started[0] = false;
    final AtomicInteger conCount = new AtomicInteger(0);

    new Thread() {
        public void run() {
            started[0] = true;
            try {
                for (int i = 0; i < NUM_ITERATIONS; ++i) {
                    Socket s = ss.accept();
                    conCount.incrementAndGet();
                    s.getOutputStream().write(PAYLOAD.getBytes());
                    s.getOutputStream().flush();
                    s.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }.start();
    Thread.sleep(50);
    Assert.assertTrue("Server not started", started[0]);

    final boolean lenOK[] = new boolean[NUM_ITERATIONS];
    final boolean dataOK[] = new boolean[NUM_ITERATIONS];
    for (int i = 0; i < NUM_ITERATIONS; i++) {
        final int ii = i;
        Socket s = null;
        try {
            s = new Socket("localhost", sinkPort);
            byte b1[] = new byte[PAYLOAD.length() / 2];
            byte b2[] = new byte[PAYLOAD.length()];
            int read1 = s.getInputStream().read(b1);
            Thread.sleep(50);
            int read2 = s.getInputStream().read(b2);
            lenOK[ii] = PAYLOAD.length() == read1 + read2;
            dataOK[ii] = PAYLOAD.equals(new String(b1, 0, read1) + new String(b2, 0, read2));
            if (!lenOK[ii] || !dataOK[ii]) {
                throw new Exception("Bad data");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (s != null) {
                s.close();
            }
        }
    }
    int ok = 0;
    for (int i = 0; i < NUM_ITERATIONS; i++) {
        ok += lenOK[i] ? 1 : 0;
    }
    Thread.sleep(50);
    for (int i = 0; i < NUM_ITERATIONS; i++) {
        Assert.assertTrue(lenOK[i]);
        Assert.assertTrue(dataOK[i]);
    }
    session.delPortForwardingR(forwardedPort);
}

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

@Test
public void testGoodNetSingle() throws Exception {
    final int port = SocketUtils.findAvailableServerSocket();
    AbstractConnectionFactory ccf = new TcpNetClientConnectionFactory("localhost", port);
    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, 100);
                latch.countDown();/*from www  . ja v a2 s.c  o  m*/
                List<Socket> sockets = new ArrayList<Socket>();
                int i = 0;
                while (true) {
                    Socket socket = server.accept();
                    ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                    ois.readObject();
                    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                    oos.writeObject("Reply" + (i++));
                    sockets.add(socket);
                }
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    ccf.setSerializer(new DefaultSerializer());
    ccf.setDeserializer(new DefaultDeserializer());
    ccf.setSoTimeout(10000);
    ccf.setSingleUse(true);
    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);
    // check the default remote timeout
    assertEquals(Long.valueOf(10000), TestUtils.getPropertyValue(gateway, "remoteTimeout", Long.class));
    gateway.setSendTimeout(123);
    // ensure this also changed the remote timeout
    assertEquals(Long.valueOf(123), TestUtils.getPropertyValue(gateway, "remoteTimeout", Long.class));
    gateway.setRemoteTimeout(60000);
    gateway.setSendTimeout(61000);
    // ensure this did NOT change the remote timeout
    assertEquals(Long.valueOf(60000), TestUtils.getPropertyValue(gateway, "remoteTimeout", Long.class));
    gateway.setRequestTimeout(60000);
    for (int i = 100; i < 200; i++) {
        gateway.handleMessage(MessageBuilder.withPayload("Test" + i).build());
    }
    Set<String> replies = new HashSet<String>();
    for (int i = 100; i < 200; i++) {
        Message<?> m = replyChannel.receive(10000);
        assertNotNull(m);
        replies.add((String) m.getPayload());
    }
    for (int i = 0; i < 100; i++) {
        assertTrue(replies.remove("Reply" + i));
    }
}

From source file:uk.ac.sanger.cgp.dbcon.support.NanoHttpd.java

/**
 * Starts a HTTP server to given port./* w  w w.  ja v  a2 s.  com*/
 * <p>
 * Throws an IOException if the socket is already in use
 */
public NanoHttpd(int port, boolean ignoreIfAlreadyBound) throws IOException {
    myTcpPort = port;

    try {
        final ServerSocket ss = new ServerSocket(myTcpPort);
        Thread t = new Thread(new Runnable() {
            public void run() {
                try {
                    while (true) {
                        if (closeServer) {
                            break;
                        }
                        new HTTPSession(ss.accept());
                    }
                    ss.close();
                } catch (IOException e) {
                    getLog().error("Problem with IO", e);
                }
            }
        });
        t.setDaemon(true);
        t.start();
    } catch (BindException e) {
        if (!ignoreIfAlreadyBound) {
            throw e;
        }
    }
}

From source file:org.eredlab.g4.ccl.net.bsd.RCommandClient.java

InputStream _createErrorStream() throws IOException {
    int localPort;
    ServerSocket server;
    Socket socket;/*  w  w  w  . j  av a 2s.c o  m*/

    localPort = MAX_CLIENT_PORT;
    server = null; // Keep compiler from barfing

    for (localPort = MAX_CLIENT_PORT; localPort >= MIN_CLIENT_PORT; --localPort) {
        try {
            server = _socketFactory_.createServerSocket(localPort, 1, getLocalAddress());
        } catch (SocketException e) {
            continue;
        }
        break;
    }

    if (localPort < MIN_CLIENT_PORT)
        throw new BindException("All ports in use.");

    _output_.write(Integer.toString(server.getLocalPort()).getBytes());
    _output_.write('\0');
    _output_.flush();

    socket = server.accept();
    server.close();

    if (isRemoteVerificationEnabled() && !verifyRemote(socket)) {
        socket.close();
        throw new IOException("Security violation: unexpected connection attempt by "
                + socket.getInetAddress().getHostAddress());
    }

    return (new SocketInputStream(socket, socket.getInputStream()));
}

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

@Test
public void testSocketSink() throws Exception {
    final ServerSocket server = new ServerSocket(0);
    final int port = server.getLocalPort();

    final AtomicReference<Throwable> error = new AtomicReference<Throwable>();

    Thread sinkRunner = new Thread("Test sink runner") {
        @Override/*from   w  w w. j a v a 2 s .c  o m*/
        public void run() {
            try {
                SocketClientSink<String> simpleSink = new SocketClientSink<>(host, port, simpleSchema, 0);
                simpleSink.open(new Configuration());
                simpleSink.invoke(TEST_MESSAGE + '\n');
                simpleSink.close();
            } catch (Throwable t) {
                error.set(t);
            }
        }
    };

    sinkRunner.start();

    Socket sk = server.accept();
    BufferedReader rdr = new BufferedReader(new InputStreamReader(sk.getInputStream()));

    String value = rdr.readLine();

    sinkRunner.join();
    server.close();

    if (error.get() != null) {
        Throwable t = error.get();
        t.printStackTrace();
        fail("Error in spawned thread: " + t.getMessage());
    }

    assertEquals(TEST_MESSAGE, value);
}