Example usage for java.net ServerSocket close

List of usage examples for java.net ServerSocket close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this socket.

Usage

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

@Test
public void testNioSingleUseWithInboundMany() throws Exception {
    final int port = SocketUtils.findAvailableServerSocket();
    final CountDownLatch latch = new CountDownLatch(1);
    final Semaphore semaphore = new Semaphore(0);
    final AtomicBoolean done = new AtomicBoolean();
    final List<Socket> serverSockets = new ArrayList<Socket>();
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            try {
                ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port, 100);
                latch.countDown();/*from   w w w.  j  av  a 2s.c  o  m*/
                for (int i = 0; i < 100; i++) {
                    Socket socket = server.accept();
                    serverSockets.add(socket);
                    semaphore.release();
                    byte[] b = new byte[9];
                    readFully(socket.getInputStream(), b);
                    b = ("Reply" + i + "\r\n").getBytes();
                    socket.getOutputStream().write(b);
                    socket.close();
                }
                server.close();
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    AbstractConnectionFactory ccf = new TcpNioClientConnectionFactory("localhost", port);
    ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer();
    ccf.setSerializer(serializer);
    ccf.setDeserializer(serializer);
    ccf.setSoTimeout(10000);
    ccf.setSingleUse(true);
    ccf.setTaskExecutor(Executors.newFixedThreadPool(100));
    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));
    int i = 0;
    try {
        for (i = 100; i < 200; i++) {
            handler.handleMessage(MessageBuilder.withPayload("Test" + i).build());
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail("Exception at " + i);
    }
    assertTrue(semaphore.tryAcquire(100, 20000, TimeUnit.MILLISECONDS));
    Set<String> replies = new HashSet<String>();
    for (i = 100; i < 200; i++) {
        Message<?> mOut = channel.receive(20000);
        assertNotNull(mOut);
        replies.add(new String((byte[]) mOut.getPayload()));
    }
    for (i = 0; i < 100; i++) {
        assertTrue("Reply" + i + " missing", replies.remove("Reply" + i));
    }
    done.set(true);
    ccf.stop();
}

From source file:org.apache.htrace.util.HTracedProcess.java

public HTracedProcess(final File binPath, final File dataDir, final String host) throws IOException {
    // Create a notifier socket bound to a random port.
    ServerSocket listener = new ServerSocket(0);
    boolean success = false;
    Process process = null;//w w  w .  jav a  2s  . co  m
    try {
        // Use a random port for the web address.  No 'scheme' yet.
        String webAddress = host + ":0";
        String logPath = new File(dataDir, "log.txt").getAbsolutePath();
        // Pass cmdline args to htraced to it uses our test dir for data.
        ProcessBuilder pb = new ProcessBuilder(binPath.toString(), "-Dlog.level=TRACE", "-Dlog.path=" + logPath,
                "-Dweb.address=" + webAddress, "-Ddata.store.clear=true",
                "-Dstartup.notification.address=localhost:" + listener.getLocalPort(),
                "-Ddata.store.directories=" + dataDir.toString());
        pb.redirectErrorStream(true);
        // Inherit STDERR/STDOUT i/o; dumps on console for now.  Can add logs later.
        pb.inheritIO();
        pb.directory(dataDir);
        //assert pb.redirectInput() == Redirect.PIPE;
        //assert pb.redirectOutput().file() == dataDir;
        process = pb.start();
        assert process.getInputStream().read() == -1;
        StartupNotificationData data = readStartupNotification(listener);
        httpAddr = data.httpAddr;
        LOG.info("Started htraced process " + data.processId + " with http " + "address " + data.httpAddr
                + ", logging to " + logPath);
        success = true;
    } finally {
        if (!success) {
            // Clean up after failure
            if (process != null) {
                process.destroy();
                process = null;
            }
        }
        delegate = process;
        listener.close();
    }
}

From source file:org.hyperic.hq.bizapp.agent.client.AgentClient.java

private void verifyAgentRunning(ServerSocket startupSock) throws AgentInvokeException {
    try {//from w  w w  . j a  v a  2s  .c  om

        Socket conn = startupSock.accept();

        DataInputStream dIs = new DataInputStream(conn.getInputStream());

        if (dIs.readInt() != 1) {
            throw new AgentInvokeException("Agent reported an error " + "while starting up");
        }

    } catch (InterruptedIOException exc) {
        throw new AgentInvokeException("Timed out waiting for Agent " + "to report startup success");
    } catch (IOException exc) {
        throw new AgentInvokeException("Agent failure while starting");
    } finally {
        try {
            startupSock.close();
        } catch (IOException exc) {
        }
    }

    try {
        this.agtCommands.ping();
    } catch (Exception exc) {
        throw new AgentInvokeException("Unable to ping agent: " + exc.getMessage());
    }
}

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

/**
 * ??sendManagerDiscoveryInfo?//from   ww  w.j  a  v a2  s.com
 * 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.wso2.carbon.automation.extensions.servers.webserver.SimpleWebServer.java

public void run() {
    ServerSocket serverSocket = null;
    Socket connectionSocket = null;
    try {/*ww  w  .  ja  va  2 s.c  om*/
        log.info("Trying to bind to localhost on port " + Integer.toString(port) + "...");
        serverSocket = new ServerSocket(port);
        log.info("Running Simple WebServer!\n");
        connectionSocket = serverSocket.accept();
        connectionSocket.setSoTimeout(30000);
        //go in a infinite loop, wait for connections, process request, send response
        while (running) {
            log.info("\nReady, Waiting for requests...\n");
            try {
                //this call waits/blocks until someone connects to the port we
                BufferedReader input;
                if (!connectionSocket.isClosed()) {
                    InetAddress client = connectionSocket.getInetAddress();
                    log.info(client.getHostName() + " connected to server.\n");
                    input = new BufferedReader(
                            new InputStreamReader(connectionSocket.getInputStream(), Charset.defaultCharset()));
                    if (input.ready()) {
                        DataOutputStream output = new DataOutputStream(connectionSocket.getOutputStream());
                        httpHandler(input, output);
                    }
                }
                //Prepare a outputStream. This will be used sending back our response
                //(header + requested file) to the client.
            } catch (Exception e) { //catch any errors, and print them
                log.info("\nError:" + e.getMessage());
                running = false;
            }
        }
    } catch (Exception e) {
        log.error("\nFatal Error:" + e.getMessage());
        running = false;
    } finally {
        try {
            if (connectionSocket != null) {
                connectionSocket.close();
                serverSocket.close();
            }
        } catch (IOException e) {
            log.error("Error while shutting down server sockets", e);
        }
    }
}

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

private void testServerExceptionGuts(int port, AbstractServerConnectionFactory factory) throws Exception {
    ServerSocket ss = null;
    try {/* w ww  . ja  v a2s.  co  m*/
        ss = ServerSocketFactory.getDefault().createServerSocket(port);
    } catch (Exception e) {
        return; // skip this test, someone grabbed the port
    }
    final AtomicReference<TcpConnectionServerExceptionEvent> theEvent = new AtomicReference<TcpConnectionServerExceptionEvent>();
    final CountDownLatch latch = new CountDownLatch(1);
    factory.setApplicationEventPublisher(new ApplicationEventPublisher() {

        @Override
        public void publishEvent(ApplicationEvent event) {
            theEvent.set((TcpConnectionServerExceptionEvent) event);
            latch.countDown();
        }

        @Override
        public void publishEvent(Object event) {

        }

    });
    factory.setBeanName("sf");
    factory.registerListener(message -> false);
    Log logger = spy(TestUtils.getPropertyValue(factory, "logger", Log.class));
    doAnswer(new DoesNothing()).when(logger).error(anyString(), any(Throwable.class));
    new DirectFieldAccessor(factory).setPropertyValue("logger", logger);

    factory.start();
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    String actual = theEvent.toString();
    assertThat(actual, containsString("cause=java.net.BindException"));
    assertThat(actual, containsString("source=" + "sf, port=" + port));

    ArgumentCaptor<String> reasonCaptor = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<Throwable> throwableCaptor = ArgumentCaptor.forClass(Throwable.class);
    verify(logger).error(reasonCaptor.capture(), throwableCaptor.capture());
    assertThat(reasonCaptor.getValue(), startsWith("Error on Server"));
    assertThat(reasonCaptor.getValue(), endsWith("; port = " + port));
    assertThat(throwableCaptor.getValue(), instanceOf(BindException.class));
    ss.close();
}

From source file:org.apache.hadoop.hbase.HBaseTestingUtility.java

/**
 * Returns a random free port and marks that port as taken. Not thread-safe. Expected to be
 * called from single-threaded test setup code/
 *//* www .ja  v  a  2s  . c  om*/
public static int randomFreePort() {
    int port = 0;
    do {
        port = randomPort();
        if (takenRandomPorts.contains(port)) {
            continue;
        }
        takenRandomPorts.add(port);

        try {
            ServerSocket sock = new ServerSocket(port);
            sock.close();
        } catch (IOException ex) {
            port = 0;
        }
    } while (port == 0);
    return port;
}

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

@Test
public void testNioNegotiateSingleNoListen() 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() {
            int i = 0;
            try {
                ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
                latch.countDown();/*  www. j av  a  2 s.  c om*/
                Socket socket = server.accept();
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                Object in = null;
                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                if (i == 0) {
                    in = ois.readObject();
                    logger.debug("read object: " + in);
                    oos.writeObject("world!");
                    ois = new ObjectInputStream(socket.getInputStream());
                    oos = new ObjectOutputStream(socket.getOutputStream());
                    in = ois.readObject();
                    logger.debug("read object: " + in);
                    oos.writeObject("world!");
                    ois = new ObjectInputStream(socket.getInputStream());
                    oos = new ObjectOutputStream(socket.getOutputStream());
                }
                in = ois.readObject();
                oos.writeObject("Reply" + (++i));
                socket.close();
                server.close();
            } catch (Exception e) {
                if (i == 0) {
                    e.printStackTrace();
                }
            }
        }
    });
    AbstractConnectionFactory ccf = new TcpNioClientConnectionFactory("localhost", port);
    ccf.setSerializer(new DefaultSerializer());
    ccf.setDeserializer(new DefaultDeserializer());
    ccf.setSoTimeout(10000);
    TcpConnectionInterceptorFactoryChain fc = new TcpConnectionInterceptorFactoryChain();
    fc.setInterceptors(new TcpConnectionInterceptorFactory[] { new HelloWorldInterceptorFactory(),
            new HelloWorldInterceptorFactory() });
    ccf.setInterceptorFactoryChain(fc);
    ccf.setSingleUse(true);
    ccf.start();
    TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
    handler.setConnectionFactory(ccf);
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    handler.handleMessage(MessageBuilder.withPayload("Test").build());
    done.set(true);
    ccf.stop();
}

From source file:org.apache.oozie.action.email.TestEmailActionExecutor.java

public void testServerTimeouts() throws Exception {
    final ServerSocket srvSocket = new ServerSocket(0);
    int srvPort = srvSocket.getLocalPort();
    Thread serverThread = new Thread() {
        @Override/*  w  w w. j a va2  s  . co m*/
        public void run() {
            try {
                Socket clientSocket = srvSocket.accept();
                // Sleep 1s (timeout applied on client is 0.1s)
                Thread.sleep(1000);
                clientSocket.getOutputStream().write(0);
                clientSocket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    serverThread.setDaemon(true);
    try {
        serverThread.start();
        EmailActionExecutor email = new EmailActionExecutor();
        Context ctx = createNormalContext("email-action");
        Services.get().get(ConfigurationService.class).getConf().setInt("oozie.email.smtp.port", srvPort);
        // Apply a 0.1s timeout to induce a very quick "Read timed out" error
        Services.get().get(ConfigurationService.class).getConf().setInt("oozie.email.smtp.socket.timeout.ms",
                100);
        try {
            email.validateAndMail(ctx, prepareEmailElement(false, false));
            fail("Should have failed with a socket timeout error!");
        } catch (Exception e) {
            Throwable rootCause = e;
            while (rootCause.getCause() != null) {
                rootCause = rootCause.getCause();
            }
            assertTrue("Expected exception type to be a SocketTimeoutException, but received: " + rootCause,
                    rootCause instanceof SocketTimeoutException);
            assertTrue("Expected error to be that of a socket read timeout, but got: " + rootCause.getMessage(),
                    rootCause.getMessage().contains("Read timed out"));
        }
    } finally {
        serverThread.interrupt();
        srvSocket.close();
    }
}

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

@Test
public void testNetNegotiateSingleNoListen() 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  av  a 2  s  .  com*/
                Socket socket = server.accept();
                int i = 0;
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                Object in = null;
                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                if (i == 0) {
                    in = ois.readObject();
                    logger.debug("read object: " + in);
                    oos.writeObject("world!");
                    ois = new ObjectInputStream(socket.getInputStream());
                    oos = new ObjectOutputStream(socket.getOutputStream());
                    in = ois.readObject();
                    logger.debug("read object: " + in);
                    oos.writeObject("world!");
                    ois = new ObjectInputStream(socket.getInputStream());
                    oos = new ObjectOutputStream(socket.getOutputStream());
                }
                in = ois.readObject();
                oos.writeObject("Reply" + (++i));
                socket.close();
                server.close();
            } 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);
    TcpConnectionInterceptorFactoryChain fc = new TcpConnectionInterceptorFactoryChain();
    fc.setInterceptors(new TcpConnectionInterceptorFactory[] { new HelloWorldInterceptorFactory(),
            new HelloWorldInterceptorFactory() });
    ccf.setInterceptorFactoryChain(fc);
    ccf.setSingleUse(true);
    ccf.start();
    TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
    handler.setConnectionFactory(ccf);
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    handler.handleMessage(MessageBuilder.withPayload("Test").build());
    done.set(true);
    ccf.stop();
}