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.openadaptor.auxil.connector.socket.SocketWriteConnector.java

/**
 * If the {@link #setRemoteHostname remoteHostname} property is set then connects to remote host
 * and returns the OutputStream from that socket. Otherwise it creates a ServerSocket
 * and waits for a connection from a client, when this happens it returns the OutputStream
 * from that socket;//  w w w.j  a  v a  2  s  .co m
        
 * @throws IOException if there was a comms error
 */
protected OutputStream getOutputStream() throws IOException {
    /* This effectively acts as the 'real' connect as the connection attempt occurs when the Socket or ServerSocket class gets instantiated
     * 
     */
    if (remoteHostname != null) {
        log.info(getId() + " connecting to " + remoteHostname + ":" + port);
        setInitiatedConnection(true);
        try {
            if (retryPeriod > 0) {
                repeatedAttempts();
            } else {
                socket = new Socket(remoteHostname, port);
            }
            configureSocket(socket);
            socketWriter = socket.getOutputStream();
            return socketWriter;
        } catch (UnknownHostException e) {
            throw new ConnectionException("UnknownHostExceptiont, " + remoteHostname + ", " + e.getMessage(), e,
                    this);
        }
    } else {
        log.info(getId() + " waiting for connection...");
        setInitiatedConnection(false);
        ServerSocket serverSocket = new ServerSocket(port);
        socket = serverSocket.accept();
        // check hostname if we only allow connections from specific hosts
        String client_host = socket.getInetAddress().getHostName();
        if (restrictedHost != null && !restrictedHost.equals(client_host)) {
            throw new ConnectionException(
                    "This component is not configured to accept connections from [" + client_host + "]", this);
        }
        log.info(getId() + " accepted connection from " + socket.getInetAddress().getHostAddress() + ":"
                + socket.getPort());
        configureSocket(socket);
        socketWriter = socket.getOutputStream();
        return socketWriter;
    }
}

From source file:org.apache.stratos.python.cartridge.agent.test.PythonCartridgeAgentTest.java

/**
 * Start server socket//ww w  . j a va 2s . c  o  m
 * @param port
 */
private void startServerSocket(final int port) {
    Thread socketThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                ServerSocket serverSocket = new ServerSocket(port);
                serverSocket.accept();
                serverSocketList.add(serverSocket);
            } 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: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);/*from w w  w . ja  va 2 s  . c  o m*/
    }
}

From source file:org.spark.examples.events.EventGenerator.java

/**
 * Launch the generator.// w  w  w. jav  a  2 s  .  c o  m
 * @param authPort Port for authentication related information.
 * @param webPort Port for web related information.
 */
public void startGenerator(int authPort, int webPort) {
    ServerSocket authSocket = null;
    ServerSocket webSocket = null;
    Socket authClient = null;
    Socket webClient = null;
    try {
        System.out.println("Waiting for clients ...");
        authSocket = new ServerSocket(authPort);
        webSocket = new ServerSocket(webPort);
        authClient = authSocket.accept();
        System.out.println("Auth client connected");
        webClient = webSocket.accept();
        System.out.println("Web client connected");
    } catch (IOException e) {
        e.printStackTrace();
    }

    sendEvents(authClient, webClient);

    try {
        if (authClient != null) {
            authClient.close();
        }
        if (webClient != null) {
            webClient.close();
        }
        if (authSocket != null) {
            authSocket.close();
        }
        if (webSocket != null) {
            webSocket.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:ext.services.network.TestNetworkUtils.java

/**
 * Test get connection url proxy with proxy.
 * //from   w  ww.  j a va2 s.  c  o m
 *
 * @throws Exception the exception
 */
public void testGetConnectionURLProxyWithProxy() throws Exception {
    final ServerSocket socket = new ServerSocket(PROXY_PORT);
    Thread thread = new Thread("ProxySocketAcceptThread") {
        @Override
        public void run() {
            try {
                while (!bStop) {
                    Socket sock = socket.accept();
                    Log.debug("Accepted connection, sending back garbage and close socket...");
                    sock.getOutputStream().write(1);
                    sock.close();
                }
            } catch (IOException e) {
                Log.error(e);
            }
        }
    };
    thread.setDaemon(true); // to finish tests even if this is still running
    thread.start();
    Log.debug("Using local port: " + socket.getLocalPort());
    try {
        // useful content when inet access is allowed
        Conf.setProperty(Const.CONF_NETWORK_NONE_INTERNET_ACCESS, "false");
        HttpURLConnection connection = NetworkUtils.getConnection(new java.net.URL(URL),
                new Proxy(Type.SOCKS, "localhost", socket.getLocalPort(), "user", "password"));
        assertNotNull(connection);
        connection.disconnect();
    } finally {
        bStop = true;
        socket.close();
        thread.join();
    }
}

From source file:org.jsslutils.extra.apachetomcat5.JSSLutilsJSSESocketFactory.java

public Socket acceptSocket(ServerSocket socket) throws IOException {
    SSLSocket asock = null;/*from   www . j  a  v a 2  s  .c  o m*/
    try {
        asock = (SSLSocket) socket.accept();
        configureClientAuth(asock);
    } catch (SSLException e) {
        throw new SocketException("SSL handshake error" + e.toString());
    }
    return asock;
}

From source file:org.apache.geode.internal.net.SSLSocketIntegrationTest.java

@Test
public void configureClientSSLSocketCanTimeOut() throws Exception {
    final Semaphore serverCoordination = new Semaphore(0);

    // configure a non-SSL server socket. We will connect
    // a client SSL socket to it and demonstrate that the
    // handshake times out
    final ServerSocket serverSocket = new ServerSocket();
    serverSocket.bind(new InetSocketAddress(SocketCreator.getLocalHost(), 0));
    Thread serverThread = new Thread() {
        public void run() {
            serverCoordination.release();
            try (Socket clientSocket = serverSocket.accept()) {
                System.out.println("server thread accepted a connection");
                serverCoordination.acquire();
            } catch (Exception e) {
                System.err.println("accept failed");
                e.printStackTrace();// w  ww.  j a  v a 2 s .  com
            }
            try {
                serverSocket.close();
            } catch (IOException e) {
                // ignored
            }
            System.out.println("server thread is exiting");
        }
    };
    serverThread.setName("SocketCreatorJUnitTest serverSocket thread");
    serverThread.setDaemon(true);
    serverThread.start();

    serverCoordination.acquire();

    SocketCreator socketCreator = SocketCreatorFactory
            .getSocketCreatorForComponent(SecurableCommunicationChannel.SERVER);

    int serverSocketPort = serverSocket.getLocalPort();
    try {
        Awaitility.await("connect to server socket").atMost(30, TimeUnit.SECONDS).until(() -> {
            try {
                Socket clientSocket = socketCreator.connectForClient(
                        SocketCreator.getLocalHost().getHostAddress(), serverSocketPort, 2000);
                clientSocket.close();
                System.err.println(
                        "client successfully connected to server but should not have been able to do so");
                return false;
            } catch (SocketTimeoutException e) {
                // we need to verify that this timed out in the handshake
                // code
                System.out.println("client connect attempt timed out - checking stack trace");
                StackTraceElement[] trace = e.getStackTrace();
                for (StackTraceElement element : trace) {
                    if (element.getMethodName().equals("configureClientSSLSocket")) {
                        System.out.println("client connect attempt timed out in the appropriate method");
                        return true;
                    }
                }
                // it wasn't in the configuration method so we need to try again
            } catch (IOException e) {
                // server socket may not be in accept() yet, causing a connection-refused
                // exception
            }
            return false;
        });
    } finally {
        serverCoordination.release();
    }
}

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

public void startLocalApiServer(final ApiMessageHandler handler) {
    try {// w  ww  .  j a  va2s  . 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:org.apache.stratos.cartridge.agent.test.JavaCartridgeAgentTest.java

/**
 * Start server socket/*from  w  ww. j av  a2  s .  c  o  m*/
 *
 * @param port
 */
private void startServerSocket(final int port) {
    Thread socketThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                ServerSocket serverSocket = new ServerSocket(port);
                serverSocketList.add(serverSocket);
                serverSocket.accept();
            } 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:org.structr.util.StructrLicenseVerifier.java

private void run() {

    try {/*from   w  ww.  ja va  2  s.co m*/

        logger.info("Listening on port {}", StructrLicenseManager.ServerPort);

        final ServerSocket serverSocket = new ServerSocket(StructrLicenseManager.ServerPort);

        serverSocket.setReuseAddress(true);

        // validation loop
        while (true) {

            try (final Socket socket = serverSocket.accept()) {

                logger.info("##### New connection from {}", socket.getInetAddress().getHostAddress());

                final InputStream is = socket.getInputStream();
                final int bufSize = 4096;

                socket.setSoTimeout(2000);

                // decrypt AES stream key using RSA block cipher
                final byte[] sessionKey = blockCipher.doFinal(IOUtils.readFully(is, 256));
                final byte[] ivSpec = blockCipher.doFinal(IOUtils.readFully(is, 256));
                final byte[] buf = new byte[bufSize];
                int count = 0;

                // initialize cipher using stream key
                streamCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(sessionKey, "AES"),
                        new IvParameterSpec(ivSpec));

                // we want to be able to control the number of bytes AND the timeout
                // of the underlying socket, so that we read the available amount of
                // data until the socket times out or we have read all the data.
                try {

                    count = is.read(buf, 0, bufSize);

                } catch (IOException ioex) {
                }

                final byte[] decrypted = streamCipher.doFinal(buf, 0, count);
                final String data = new String(decrypted, "utf-8");

                // transform decrypted data into a Map<String, String>
                final List<Pair> pairs = split(data).stream().map(StructrLicenseVerifier::keyValue)
                        .collect(Collectors.toList());
                final Map<String, String> map = pairs.stream().filter(Objects::nonNull)
                        .collect(Collectors.toMap(Pair::getLeft, Pair::getRight));

                // validate data against customer database
                if (isValid(map)) {

                    // send signatur of name field back to client
                    final String name = (String) map.get(StructrLicenseManager.NameKey);
                    final byte[] response = name.getBytes("utf-8");

                    // respond with the signature of the data sent to us
                    socket.getOutputStream().write(sign(response));
                    socket.getOutputStream().flush();

                } else {

                    logger.info("License verification failed.");
                }

                socket.getOutputStream().close();

            } catch (Throwable t) {
                logger.warn("Unable to verify license: {}", t.getMessage());
            }
        }

    } catch (Throwable t) {
        logger.warn("Unable to verify license: {}", t.getMessage());
    }
}