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.connection.TcpNioConnectionTests.java

@Test
public void testWriteTimeout() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final CountDownLatch done = new CountDownLatch(1);
    final AtomicReference<ServerSocket> serverSocket = new AtomicReference<ServerSocket>();
    Executors.newSingleThreadExecutor().execute(() -> {
        try {/*from  w  ww.  ja v  a2 s . c  om*/
            ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(0);
            logger.debug(testName.getMethodName() + " starting server for " + server.getLocalPort());
            serverSocket.set(server);
            latch.countDown();
            Socket s = server.accept();
            // block so we fill the buffer
            done.await(10, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    });
    assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
    TcpNioClientConnectionFactory factory = new TcpNioClientConnectionFactory("localhost",
            serverSocket.get().getLocalPort());
    factory.setApplicationEventPublisher(nullPublisher);
    factory.setSoTimeout(1000);
    factory.start();
    try {
        TcpConnection connection = factory.getConnection();
        connection.send(MessageBuilder.withPayload(new byte[1000000]).build());
    } catch (Exception e) {
        assertTrue(
                "Expected SocketTimeoutException, got " + e.getClass().getSimpleName() + ":" + e.getMessage(),
                e instanceof SocketTimeoutException);
    }
    done.countDown();
    serverSocket.get().close();
}

From source file:org.springframework.integration.ip.tcp.connection.TcpNioConnectionTests.java

@Test
public void testReadTimeout() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final CountDownLatch done = new CountDownLatch(1);
    final AtomicReference<ServerSocket> serverSocket = new AtomicReference<ServerSocket>();
    Executors.newSingleThreadExecutor().execute(() -> {
        try {/*from w  w w . j a  v a  2 s .  co  m*/
            ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(0);
            logger.debug(testName.getMethodName() + " starting server for " + server.getLocalPort());
            serverSocket.set(server);
            latch.countDown();
            Socket socket = server.accept();
            byte[] b = new byte[6];
            readFully(socket.getInputStream(), b);
            // block to cause timeout on read.
            done.await(10, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    });
    assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
    TcpNioClientConnectionFactory factory = new TcpNioClientConnectionFactory("localhost",
            serverSocket.get().getLocalPort());
    factory.setApplicationEventPublisher(nullPublisher);
    factory.setSoTimeout(1000);
    factory.start();
    try {
        TcpConnection connection = factory.getConnection();
        connection.send(MessageBuilder.withPayload("Test").build());
        int n = 0;
        while (connection.isOpen()) {
            Thread.sleep(100);
            if (n++ > 200) {
                break;
            }
        }
        assertTrue(!connection.isOpen());
    } catch (Exception e) {
        fail("Unexpected exception " + e);
    }
    done.countDown();
    serverSocket.get().close();
}

From source file:UniqueInstance.java

/**
 * Essaye de dmarrer le gestionnaire d'instance unique. Si l'initialisation a russi, c'est que l'instance est
 * unique. Sinon, c'est qu'une autre instance de l'application est dj lance. L'appel de cette mthode prvient
 * l'application dj lance qu'une autre vient d'essayer de se connecter.
 *
 * @return {@code true} si l'instance de l'application est unique.
 *///  w w w.j  a  v  a 2  s  . c o m
public boolean launch() {
    /* Indique si l'instance du programme est unique. */
    boolean unique;

    try {
        /* On cre une socket sur le port dfini. */
        final ServerSocket server = new ServerSocket(port);

        /* Si la cration de la socket russit, c'est que l'instance du programme est unique, aucune autre n'existe. */
        unique = true;

        /* Si il y a des actions  faire lorsqu'une autre instance essaye de dmarrer... */
        if (runOnReceive != null) {

            /* On lance un Thread d'coute sur ce port. */
            Thread portListenerThread = new Thread() {

                @Override
                public void run() {
                    /* Tant que l'application est lance... */
                    while (true) {
                        try {
                            /* On attend qu'une socket se connecte sur le serveur. */
                            final Socket socket = server.accept();

                            /* Si une socket est connecte, on coute le message envoy dans un nouveau Thread. */
                            new Thread() {

                                @Override
                                public void run() {
                                    receive(socket);
                                }
                            }.start();
                        } catch (IOException e) {
                            Logger.getLogger("UniqueInstance")
                                    .warning("Attente de connexion de socket choue.");
                        }
                    }
                }
            };

            /* Le Thread d'coute de port est dmon. */
            portListenerThread.setDaemon(true);

            /* On dmarre le Thread. */
            portListenerThread.start();
        }
    } catch (IOException e) {
        /* Si la cration de la socket choue, c'est que l'instance de n'est pas unique, une autre n'existe. */
        unique = false;

        /* Si des actions sont prvues par l'instance dj lance... */
        if (runOnReceive != null) {
            /*
             * Dans ce cas, on envoie un message  l'autre instance de l'application pour lui demander d'avoir le
             * focus (par exemple).
             */
            send();
        }
    }
    return unique;
}

From source file:org.springframework.integration.ip.tcp.connection.TcpNioConnectionTests.java

@Test
public void testMemoryLeak() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<ServerSocket> serverSocket = new AtomicReference<ServerSocket>();
    Executors.newSingleThreadExecutor().execute(() -> {
        try {//w w w. j  a v a  2 s . c  o m
            ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(0);
            logger.debug(testName.getMethodName() + " starting server for " + server.getLocalPort());
            serverSocket.set(server);
            latch.countDown();
            Socket socket = server.accept();
            byte[] b = new byte[6];
            readFully(socket.getInputStream(), b);
        } catch (Exception e) {
            e.printStackTrace();
        }
    });
    assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
    TcpNioClientConnectionFactory factory = new TcpNioClientConnectionFactory("localhost",
            serverSocket.get().getLocalPort());
    factory.setApplicationEventPublisher(nullPublisher);
    factory.setNioHarvestInterval(100);
    factory.start();
    try {
        TcpConnection connection = factory.getConnection();
        Map<SocketChannel, TcpNioConnection> connections = factory.getConnections();
        assertEquals(1, connections.size());
        connection.close();
        assertTrue(!connection.isOpen());
        TestUtils.getPropertyValue(factory, "selector", Selector.class).wakeup();
        int n = 0;
        while (connections.size() > 0) {
            Thread.sleep(100);
            if (n++ > 100) {
                break;
            }
        }
        assertEquals(0, connections.size());
    } catch (Exception e) {
        e.printStackTrace();
        fail("Unexpected exception " + e);
    }
    factory.stop();
    serverSocket.get().close();
}

From source file:com.clustercontrol.agent.Agent.java

/**
 * ??sendManagerDiscoveryInfo?//from  w  w w. j  a v a 2s .c om
 * TCP 24005?????????IP?
 * 
 * @throws Exception
 */
private String receiveManagerDiscoveryInfo() throws Exception {
    int default_port = 24005;
    String portStr = AgentProperties.getProperty("discovery.pingport", Integer.toString(default_port));
    int port = Integer.parseInt(portStr);
    if (port < 1 || port > 65535) {
        port = default_port;
    }
    ServerSocket servSock = null;
    Socket clntSock = null;

    final int BUFSIZE = 256;
    int tmpRecvMsgSize = 0;
    int recvMsgSize = 0;
    byte[] receiveBuf = new byte[BUFSIZE];
    String recvMsg = "";

    try {
        servSock = new ServerSocket(port);

        // ????
        clntSock = servSock.accept();
        m_log.info("connecting to " + clntSock.getRemoteSocketAddress().toString());

        InputStream in = clntSock.getInputStream();
        OutputStream out = clntSock.getOutputStream();

        while ((tmpRecvMsgSize = in.read(receiveBuf)) != -1) {
            out.write(receiveBuf, 0, tmpRecvMsgSize);
            recvMsgSize = tmpRecvMsgSize;
        }

        recvMsg = new String(receiveBuf, 0, recvMsgSize);
        m_log.info("receive message : " + recvMsg);
    } catch (Exception e) {
        m_log.warn("receiveManagerIp " + e.getClass().getSimpleName() + ", " + e.getMessage());
        throw e;
    } finally {
        try {
            if (clntSock != null) {
                clntSock.close();
            }
        } catch (Exception e) {
            m_log.warn("receiveManagerIp: " + e);
        }
        try {
            if (servSock != null) {
                servSock.close();
            }
        } catch (Exception e) {
            m_log.warn("receiveManagerIp: " + e);
        }
    }
    return recvMsg;
}

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

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

    final SocketClientSink<String> simpleSink = new SocketClientSink<>(host, port, simpleSchema, 0, true);
    simpleSink.open(new Configuration());

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

    Thread sinkRunner = new Thread("Test sink runner") {
        @Override/*from w  w  w.j  a  va2 s.  co  m*/
        public void run() {
            try {
                // need two messages here: send a fin to cancel the client state:FIN_WAIT_2 while the server is CLOSE_WAIT
                simpleSink.invoke(TEST_MESSAGE + '\n');
            } 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();
    simpleSink.close();
    server.close();

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

    assertEquals(TEST_MESSAGE, value);
}

From source file:org.freedesktop.dbus.Transport.java

@SuppressWarnings("resource")
public void connect(BusAddress address, int timeout) throws IOException {
    log.info("Connecting to " + address);
    OutputStream out = null;//ww w  .j  ava2s  .  com
    InputStream in = null;
    AFUNIXSocket us = null;
    Socket s = null;
    int mode = 0;
    int types = 0;
    if ("unix".equals(address.getType())) {
        types = SASL.AUTH_EXTERNAL;
        File sockFile = null;
        boolean abstractSock = false;
        if (null != address.getParameter("abstract")) {
            sockFile = new File(address.getParameter("abstract"));
            abstractSock = true;
        } else if (null != address.getParameter("path")) {
            sockFile = new File(address.getParameter("path"));
        }

        if (null != address.getParameter("listen")) {
            mode = SASL.MODE_SERVER;
            AFUNIXServerSocket uss = AFUNIXServerSocket.newInstance();
            uss.bind(new AFUNIXSocketAddress(sockFile, abstractSock));
            uss.setPassCred(true);
            s = uss.accept();
        } else {
            mode = SASL.MODE_CLIENT;
            us = AFUNIXSocket.newInstance();

            us.connect(new AFUNIXSocketAddress(sockFile, abstractSock));
            us.setPassCred(true);
            s = us;
        }

    } else if ("tcp".equals(address.getType())) {
        types = SASL.AUTH_SHA;
        if (null != address.getParameter("listen")) {
            mode = SASL.MODE_SERVER;
            ServerSocket ss = new ServerSocket();
            ss.bind(new InetSocketAddress(address.getParameter("host"),
                    Integer.parseInt(address.getParameter("port"))));
            s = ss.accept();
        } else {
            mode = SASL.MODE_CLIENT;
            s = new Socket();
            s.connect(new InetSocketAddress(address.getParameter("host"),
                    Integer.parseInt(address.getParameter("port"))));
        }
    } else {
        throw new IOException("unknown address type " + address.getType());
    }

    in = s.getInputStream();
    out = s.getOutputStream();

    if (!(new SASL()).auth(mode, types, address.getParameter("guid"), out, in, us)) {
        out.close();
        in.close();
        s.close();
        throw new IOException("Failed to auth");
    }

    if (log.isTraceEnabled()) {
        log.trace("Setting timeout to " + timeout + " on Socket");
    }
    s.setSoTimeout(timeout);

    this.mout = new MessageWriter(out);
    this.min = new MessageReader(in);

    log.info("Connection open");
}

From source file:org.apache.isis.objectstore.nosql.db.file.server.FileServer.java

private void startSecondary() {
    final String serviceHost = config.getString("fileserver.sync-host", DEFAULT_HOST);
    final int servicePort = config.getInt("fileserver.sync-port", DEFAULT_SYNC_PORT);

    Util.ensureDirectoryExists();
    ServerSocket socket = null;
    try {/*from w  w w  .j a  v a2 s  .  c o  m*/
        LOG.debug("setting up syncing socket on " + serviceHost + ":" + servicePort);
        final InetAddress address = InetAddress.getByName(serviceHost);
        socket = new ServerSocket(servicePort, 0, address);
        LOG.info(
                "listenting on " + socket.getInetAddress().getHostAddress() + " port " + socket.getLocalPort());
        LOG.debug("listenting on " + socket);
        do {
            syncConnection(socket.accept(), 0);
        } while (awaitConnections);
    } catch (final UnknownHostException e) {
        LOG.error("Unknown host " + serviceHost, e);
        System.exit(0);
    } catch (final IOException e) {
        LOG.error("start failure - networking not set up for " + serviceHost, e);
        System.exit(0);
    } catch (final RuntimeException e) {
        LOG.error("start failure", e);
        System.exit(0);
    }
}

From source file:de.th.wildau.dsc.sne.webserver.WebServer.java

/**
 * Web server / main constructor./*from w w w  .j a v a2 s  .c om*/
 * 
 * @param startArguments
 */
public WebServer(String[] startArguments) {

    loadConfiguration(startArguments);
    Log.debug(Configuration.getInstance().toString());

    Log.debug("Information about the OS: " + System.getProperty("os.name") + " - "
            + System.getProperty("os.version") + " - " + System.getProperty("os.arch"));

    if (Configuration.getConfig().getProxyHost() != null) {
        Log.debug("setup proxy configuration");
        System.setProperty("http.proxyHost", Configuration.getConfig().getProxyHost());
        System.setProperty("http.proxyPort", String.valueOf(Configuration.getConfig().getProxyPort()));
    }

    Log.debug("find supported scripting languages");
    supportedScriptLanguages = Collections.unmodifiableList(ScriptExecutor.getSupportedScriptLanguages());
    Log.debug("Supported Script Languages " + Arrays.toString(supportedScriptLanguages.toArray()));

    Log.info("instantiating web server");
    try {
        ServerSocket server = new ServerSocket(Configuration.getConfig().getServerPort());
        Log.debug("bound port " + Configuration.getConfig().getServerPort());

        int corePoolSize = Runtime.getRuntime().availableProcessors();
        int maxPoolSize = (2 * corePoolSize) + 1;
        Log.debug("core/max pool size: " + corePoolSize + "/" + maxPoolSize);
        LinkedBlockingQueue<Runnable> workerQueue = new LinkedBlockingQueue<Runnable>();
        long keepAliveTime = 30;
        /*
         * keepAliveTime - If the pool currently has more than corePoolSize
         * threads, excess threads will be terminated if they have been idle
         * for more than the keepAliveTime.
         */

        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime,
                TimeUnit.SECONDS, workerQueue);
        threadPool.prestartAllCoreThreads();

        Socket socket = null;
        while (true) {

            try {
                socket = server.accept();
                Log.info(socket.getInetAddress().getHostName() + " client request");
                threadPool.execute(new HttpHandler(socket));
                Log.debug("current threads: " + threadPool.getActiveCount());
            } catch (final IOException ex) {
                Log.error("Connection failed!", ex);
            } catch (final RejectedExecutionException ex) {
                // XXX [sne] RejectedExecutionException
                // http://stackoverflow.com/questions/1519725/why-does-executors-newcachedthreadpool-throw-java-util-concurrent-rejectedexecut
                // http://www.javamex.com/tutorials/threads/thread_pools_queues.shtml
                // http://stackoverflow.com/questions/2001086/how-to-make-threadpoolexecutors-submit-method-block-if-it-is-saturated
                Log.error("RejectedExecutionException", ex);
                socket.close();
            } catch (final Exception ex) {
                Log.fatal("Unknown error!", ex);
            }
        }
    } catch (final IOException ex) {
        Log.fatal("Can not start the server!", ex);
        System.err.println("Can not start the server! " + ex.getMessage());
    } catch (final Exception ex) {
        Log.fatal("Unknown error!", ex);
    }
}

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

@Test
public void testNetSerial() 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();//ww  w.  j  a  va 2s .  c om
                Socket socket = server.accept();
                int i = 0;
                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.start();
    TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
    handler.setConnectionFactory(ccf);
    TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter();
    adapter.setConnectionFactory(ccf);
    QueueChannel channel = new QueueChannel();
    adapter.setOutputChannel(channel);
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    handler.handleMessage(MessageBuilder.withPayload("Test").build());
    handler.handleMessage(MessageBuilder.withPayload("Test").build());
    Message<?> mOut = channel.receive(10000);
    assertNotNull(mOut);
    assertEquals("Reply1", mOut.getPayload());
    mOut = channel.receive(10000);
    assertNotNull(mOut);
    assertEquals("Reply2", mOut.getPayload());
    done.set(true);
    ccf.stop();
}