Example usage for java.net Socket Socket

List of usage examples for java.net Socket Socket

Introduction

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

Prototype

public Socket() 

Source Link

Document

Creates an unconnected Socket.

Usage

From source file:com.linecorp.armeria.server.ServerTest.java

@Test(timeout = idleTimeoutMillis * 5)
public void testIdleTimeoutByContentSent() throws Exception {
    try (Socket socket = new Socket()) {
        socket.setSoTimeout((int) (idleTimeoutMillis * 4));
        socket.connect(server().activePort().get().localAddress());
        PrintWriter outWriter = new PrintWriter(socket.getOutputStream(), false);
        outWriter.print("POST / HTTP/1.1\r\n");
        outWriter.print("Connection: Keep-Alive\r\n");
        outWriter.print("\r\n");
        outWriter.flush();/*from  www . jav  a2  s  . com*/

        long lastWriteNanos = System.nanoTime();
        //read until EOF
        while (socket.getInputStream().read() != -1) {
            continue;
        }

        long elapsedTimeMillis = TimeUnit.MILLISECONDS.convert(System.nanoTime() - lastWriteNanos,
                TimeUnit.NANOSECONDS);
        assertThat(elapsedTimeMillis, is(greaterThanOrEqualTo(idleTimeoutMillis)));
    }
}

From source file:org.hyperic.hq.plugin.netservices.NetServicesCollector.java

public SocketWrapper getSocketWrapper(boolean acceptUnverifiedCertificatesOverride) throws IOException {
    if (isSSL()) {
        // Sometimes we may want to override what's set in the keystore config...mostly for init purposes...
        boolean accept = acceptUnverifiedCertificatesOverride ? true : keystoreConfig.isAcceptUnverifiedCert();
        SSLProvider sslProvider = new DefaultSSLProviderImpl(keystoreConfig, accept);
        SSLSocketFactory factory = sslProvider.getSSLSocketFactory();
        Socket socket = factory.createSocket();

        socket.connect(getSocketAddress(), getTimeoutMillis());
        socket.setSoTimeout(getTimeoutMillis());
        ((SSLSocket) socket).startHandshake();

        return new SocketWrapper(socket);
    } else {/*from  w  w w  . j a  va  2  s. c  om*/
        Socket socket = new Socket();
        connect(socket);
        return new SocketWrapper(socket);
    }
}

From source file:org.psit.transwatcher.TransWatcher.java

private void startConnectionKeepAliveWatchDog(final Socket newImageListenerSocket) {
    watchDogThread = new Thread(new Runnable() {
        public void run() {
            try {
                while (true) {
                    Thread.sleep(5000);
                    InetSocketAddress addr = new InetSocketAddress(newImageListenerSocket.getInetAddress(), 80);
                    Socket s = new Socket();
                    s.connect(addr, 1000);
                    s.close();//from   ww  w.j ava 2s  .  c o  m
                    notifyMessage("WatchDog ping.");
                }
            } catch (InterruptedException e) {
                notifyMessage("WatchDog interrupted");
            } catch (IOException e) {
                notifyMessage("WatchDog: Connection to card lost.");
                try {
                    newImageListenerSocket.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                e.printStackTrace();
            }

        };
    }, "ConnectionWatchDog");
    watchDogThread.start();
}

From source file:de.tum.frm2.nicos_android.nicos.NicosClient.java

public void connect(ConnectionData connData, Object[] eventmask) throws RuntimeException {
    if (connected) {
        throw new RuntimeException("client already connected");
    }/*from w w  w . ja  v a  2 s  . c  om*/
    disconnecting = false;

    SocketAddress sockaddr;
    try {
        // If ANY code of this scope failes, communication is entirely impossible.
        // That means, no need to catch all exceptions one by one.
        InetAddress addr = InetAddress.getByName(connData.getHost());
        sockaddr = new InetSocketAddress(addr, connData.getPort());

        // Initialize empty socket.
        socket = new Socket();

        // Connects this socket to the server with a specified timeout value
        // If timeout occurs, SocketTimeoutException is thrown
        socket.connect(sockaddr, TIMEOUT);
        socketOut = socket.getOutputStream();
        socketIn = socket.getInputStream();

        // Write client identification: we are a new client
        socketOut.write(client_id);
    } catch (Exception e) {
        String msg;
        if (e instanceof IOException) {
            // "null reference" error messages won't help the user.
            msg = "Socket communication failed (server not responding).";
        } else {
            msg = "Server connection failed: " + e.getMessage() + ".";
        }
        signal("failed", msg);
        return;
    }

    // read banner
    try {
        TupleOfTwo<Byte, Object> response = _read();
        byte ret = response.getFirst();
        if (ret != daemon.STX) {
            throw new ProtocolError("invalid response format");
        }
        nicosBanner = (HashMap) response.getSecond();
        if (!nicosBanner.containsKey("daemon_version")) {
            throw new ProtocolError("daemon version missing from response");
        }
        int daemon_proto = (int) nicosBanner.get("protocol_version");
        if (!daemon.isProtoVersionCompatible(daemon_proto)) {
            throw new ProtocolError("daemon uses protocol " + String.valueOf(daemon_proto)
                    + ", but this client requires protocol " + String.valueOf(daemon.PROTO_VERSIONS[0]));
        }
    } catch (Exception e) {
        signal("failed", "Server(" + connData.getHost() + ":" + String.valueOf(connData.getPort())
                + ") handshake failed: " + e.getMessage());
        return;
    }

    // log-in sequence
    char[] password = connData.getPassword();
    Object unwrap = nicosBanner.get("pw_hashing");
    String pw_hashing = "sha1";
    if (unwrap != null) {
        pw_hashing = unwrap.toString();
    }

    String encryptedPassword = null;
    boolean supportsRSA = false;
    try {
        String rsaSupportString = pw_hashing.substring(0, 4);
        supportsRSA = rsaSupportString.equals("rsa,");
    } catch (StringIndexOutOfBoundsException e) {
        // Does not start with "rsa," -> does not support RSA encryption.
        // boolean supportsRSA stays at false.
    }
    if (supportsRSA) {
        byte[] keyBytes = Base64.decode(nicosBanner.get("rsakey").toString(), Base64.DEFAULT);
        String publicKeyString = new String(keyBytes, StandardCharsets.UTF_8);
        PublicKey publicKey = extractPublicKey(publicKeyString);

        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
        } catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException e) {
            // Cannot happen.
        }
        try {
            if (cipher != null) {
                cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            } else {
                throw new InvalidKeyException();
            }
        } catch (InvalidKeyException e) {
            throw new RuntimeException("The server's RSA key is invalid or incompatible.");
        }

        byte[] encrypted;
        try {
            encrypted = cipher.doFinal(String.valueOf(password).getBytes());
        } catch (IllegalBlockSizeException | BadPaddingException e) {
            e.printStackTrace();
            encrypted = new byte[0];
        }
        encryptedPassword = "RSA:" + Base64.encodeToString(encrypted, Base64.DEFAULT);
    }

    if (pw_hashing.equals("sha1")) {
        encryptedPassword = new String(Hex.encodeHex(DigestUtils.sha1(String.valueOf(password))));
    }

    else if (pw_hashing.equals("md5")) {
        encryptedPassword = new String(Hex.encodeHex(DigestUtils.md5(String.valueOf(password))));
    }

    HashMap<String, String> credentials = new HashMap<>();
    credentials.put("login", connData.getUser());
    credentials.put("passwd", encryptedPassword);
    credentials.put("display", "");

    // Server requires credentials to be wrapped in a tuple with 1 item
    // e.g. python: payload = (credentials,)
    // Pyrolite library matches java.lang.Object arrays to tuples with the array's length.
    Object[] data = { credentials };
    Object untypedAuthResponse = ask("authenticate", data);
    if (untypedAuthResponse == null) {
        return;
    }

    // Login was successful.
    HashMap authResponse = (HashMap) untypedAuthResponse;
    user_level = (int) authResponse.get("user_level");

    if (eventmask != null) {
        tell("eventmask", eventmask);
    }

    // connect to event port
    eventSocket = new Socket();
    try {
        eventSocket.connect(sockaddr);
        OutputStream eventSocketOut = eventSocket.getOutputStream();
        eventSocketIn = eventSocket.getInputStream();
        eventSocketOut.write(client_id);
    } catch (IOException e) {
        signal("failed", "Event connection failed: " + e.getMessage() + ".", e);
        return;
    }

    // Start event handler
    final Thread event_thread = new Thread(new Runnable() {
        @Override
        public void run() {
            // equals event_handler.
            event_handler();
        }
    });
    event_thread.start();

    connected = true;
    viewonly = connData.getViewonly();
    signal("connected");
}

From source file:com.adito.server.ServerLock.java

private void checkStatus() {
    Socket socket = null;//www.  j  av a  2  s  .c  o m
    try {
        int timeout = 5000; // 5 seconds
        if (log.isInfoEnabled())
            log.info("Connecting to " + bindAddress + ":" + port + " to see if a server is already running.");
        SocketAddress socketAddress = new InetSocketAddress(bindAddress, port);
        socket = new Socket();
        socket.connect(socketAddress, timeout);
        locked = true;
    } catch (Exception e) {
        locked = false;
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (Exception e) {

            }
        }
    }
}