Example usage for java.net Socket connect

List of usage examples for java.net Socket connect

Introduction

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

Prototype

public void connect(SocketAddress endpoint, int timeout) throws IOException 

Source Link

Document

Connects this socket to the server with a specified timeout value.

Usage

From source file:org.apache.zeppelin.interpreter.remote.RemoteInterpreterUtils.java

public static boolean checkIfRemoteEndpointAccessible(String host, int port) {
    try {/*from w ww  .  ja  v a  2s. c om*/
        Socket discover = new Socket();
        discover.setSoTimeout(1000);
        discover.connect(new InetSocketAddress(host, port), 1000);
        discover.close();
        return true;
    } catch (ConnectException cne) {
        // end point is not accessible
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Remote endpoint '" + host + ":" + port + "' is not accessible "
                    + "(might be initializing): " + cne.getMessage());
        }
        return false;
    } catch (IOException ioe) {
        // end point is not accessible
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Remote endpoint '" + host + ":" + port + "' is not accessible "
                    + "(might be initializing): " + ioe.getMessage());
        }
        return false;
    }
}

From source file:totalcross.android.ConnectionManager4A.java

public static boolean isInternetAccessible() {
    try {/*w ww . ja  va 2s . c o m*/
        InetSocketAddress isa = new InetSocketAddress(InetAddress.getByName("www.google.com"), 80);
        Socket s = new Socket();
        s.connect(isa, 30 * 1000);
        s.close();
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:org.csource.fastdfs.ClientGlobal.java

/**
* construct Socket object/*from  ww  w.  j  a  v a2  s. c o m*/
* @param ip_addr ip address or hostname
* @param port port number
* @return connected Socket object
*/
public static Socket getSocket(String ip_addr, int port) throws IOException {
    Socket sock = new Socket();
    sock.setSoTimeout(ClientGlobal.g_network_timeout);
    sock.connect(new InetSocketAddress(ip_addr, port), ClientGlobal.g_connect_timeout);
    return sock;
}

From source file:org.csource.fastdfs.ClientGlobal.java

/**
* construct Socket object/*from  ww w  .  j a  v a  2s .com*/
* @param addr InetSocketAddress object, including ip address and port
* @return connected Socket object
*/
public static Socket getSocket(InetSocketAddress addr) throws IOException {
    Socket sock = new Socket();
    sock.setSoTimeout(ClientGlobal.g_network_timeout);
    sock.connect(addr, ClientGlobal.g_connect_timeout);
    return sock;
}

From source file:net.arccotangent.pacchat.net.Client.java

public static void sendMessage(String msg, String ip_address) {
    client_log.i("Sending message to " + ip_address);
    client_log.i("Connecting to server...");

    PublicKey pub;//w w w. ja v a  2  s.  c o  m
    PrivateKey priv;
    Socket socket;
    BufferedReader input;
    BufferedWriter output;

    client_log.i("Checking for recipient's public key...");
    if (KeyManager.checkIfIPKeyExists(ip_address)) {
        client_log.i("Public key found.");
    } else {
        client_log.i("Public key not found, requesting key from their server.");
        try {
            Socket socketGetkey = new Socket();
            socketGetkey.connect(new InetSocketAddress(InetAddress.getByName(ip_address), Server.PORT), 1000);
            BufferedReader inputGetkey = new BufferedReader(
                    new InputStreamReader(socketGetkey.getInputStream()));
            BufferedWriter outputGetkey = new BufferedWriter(
                    new OutputStreamWriter(socketGetkey.getOutputStream()));

            outputGetkey.write("301 getkey");
            outputGetkey.newLine();
            outputGetkey.flush();

            String pubkeyB64 = inputGetkey.readLine();
            byte[] pubEncoded = Base64.decodeBase64(pubkeyB64);
            X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubEncoded);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");

            outputGetkey.close();
            inputGetkey.close();

            KeyManager.saveKeyByIP(ip_address, keyFactory.generatePublic(pubSpec));
        } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
            client_log.e("Error saving recipient's key!");
            e.printStackTrace();
        }
    }

    try {
        socket = new Socket();
        socket.connect(new InetSocketAddress(InetAddress.getByName(ip_address), Server.PORT), 1000);
        input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    } catch (SocketTimeoutException e) {
        client_log.e("Connection to server timed out!");
        e.printStackTrace();
        return;
    } catch (ConnectException e) {
        client_log.e("Connection to server was refused!");
        e.printStackTrace();
        return;
    } catch (UnknownHostException e) {
        client_log.e("You entered an invalid IP address!");
        e.printStackTrace();
        return;
    } catch (IOException e) {
        client_log.e("Error connecting to server!");
        e.printStackTrace();
        return;
    }

    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    pub = KeyManager.loadKeyByIP(ip_address);
    priv = Main.getKeypair().getPrivate();

    String cryptedMsg = MsgCrypto.encryptAndSignMessage(msg, pub, priv);
    try {
        client_log.i("Sending message to recipient.");
        output.write("200 encrypted message");
        output.newLine();
        output.write(cryptedMsg);
        output.newLine();
        output.flush();

        String ack = input.readLine();
        switch (ack) {
        case "201 message acknowledgement":
            client_log.i("Transmission successful, received server acknowledgement.");
            break;
        case "202 unable to decrypt":
            client_log.e(
                    "Transmission failure! Server reports that the message could not be decrypted. Did your keys change? Asking recipient for key update.");
            kuc_id++;
            KeyUpdateClient kuc = new KeyUpdateClient(kuc_id, ip_address);
            kuc.start();
            break;
        case "203 unable to verify":
            client_log.w("**********************************************");
            client_log.w(
                    "Transmission successful, but the receiving server reports that the authenticity of the message could not be verified!");
            client_log.w(
                    "Someone may be tampering with your connection! This is an unlikely, but not impossible scenario!");
            client_log.w(
                    "If you are sure the connection was not tampered with, consider requesting a key update.");
            client_log.w("**********************************************");
            break;
        case "400 invalid transmission header":
            client_log.e(
                    "Transmission failure! Server reports that the message is invalid. Try updating your software and have the recipient do the same. If this does not fix the problem, report the error to developers.");
            break;
        default:
            client_log.w("Server responded with unexpected code: " + ack);
            client_log.w("Transmission might not have been successful.");
            break;
        }

        output.close();
        input.close();
    } catch (IOException e) {
        client_log.e("Error sending message to recipient!");
        e.printStackTrace();
    }
}

From source file:org.apache.stratos.cartridge.agent.util.CartridgeAgentUtils.java

public static boolean checkPortsActive(String ipAddress, List<Integer> ports) {
    //List<Integer> ports = CartridgeAgentConfiguration.getInstance().getPorts();
    if (ports.size() == 0) {
        throw new RuntimeException("No ports found");
    }/*from  ww w  .  ja  va  2  s .c o  m*/
    for (int port : ports) {
        Socket socket = null;
        try {
            SocketAddress httpSockaddr = new InetSocketAddress(ipAddress, port);
            socket = new Socket();
            socket.connect(httpSockaddr, 5000);
            if (log.isDebugEnabled()) {
                log.debug(String.format("Port %s is active", port));
            }
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.debug(String.format("Port %s is not active", port));
            }
            return false;
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                }
            }
        }
    }
    return true;
}

From source file:org.apache.hadoop.hdfs.BlockReaderTestUtil.java

/**
 * Get a BlockReader for the given block.
 *///ww w .ja v a2s.c  om
public static BlockReader getBlockReader(MiniDFSCluster cluster, LocatedBlock testBlock, int offset,
        int lenToRead) throws IOException {
    InetSocketAddress targetAddr = null;
    ExtendedBlock block = testBlock.getBlock();
    DatanodeInfo[] nodes = testBlock.getLocations();
    targetAddr = NetUtils.createSocketAddr(nodes[0].getXferAddr());

    final DistributedFileSystem fs = cluster.getFileSystem();
    return new BlockReaderFactory(fs.getClient().getConf()).setInetSocketAddress(targetAddr)
            .setExtendedBlock(block).setFileName(targetAddr.toString() + ":" + block.getBlockId())
            .setBlockToken(testBlock.getBlockToken()).setStartOffset(offset).setLength(lenToRead)
            .setVerifyChecksum(true).setClientName("BlockReaderTestUtil").setDatanodeInfo(nodes[0])
            .setClientCacheContext(ClientContext.getFromConf(fs.getConf()))
            .setCachingStrategy(CachingStrategy.newDefaultStrategy()).setConfiguration(fs.getConf())
            .setAllowShortCircuitLocalReads(true).setTracer(FsTracer.get(fs.getConf()))
            .setRemotePeerFactory(new RemotePeerFactory() {
                @Override
                public SocketFactory getSocketFactory(Configuration conf) throws IOException {
                    return NetUtils.getDefaultSocketFactory(conf);
                }

                @Override
                public Peer newConnectedPeer(InetSocketAddress addr, Token<BlockTokenIdentifier> blockToken,
                        DatanodeID datanodeId) throws IOException {
                    Peer peer = null;
                    Socket sock = getSocketFactory(fs.getConf()).createSocket();
                    try {
                        sock.connect(addr, HdfsServerConstants.READ_TIMEOUT);
                        sock.setSoTimeout(HdfsServerConstants.READ_TIMEOUT);
                        peer = TcpPeerServer.peerFromSocket(sock);
                    } finally {
                        if (peer == null) {
                            IOUtils.closeQuietly(sock);
                        }
                    }
                    return peer;
                }
            }).build();
}

From source file:org.jkcsoft.java.util.TcpHelper.java

public static String connectToServer(String host, int port, int timeoutMillis) {
    String fromServer = "";

    BufferedReader reader = null;
    PrintWriter writer = null;/*from w w  w .ja v  a 2s .c om*/
    Socket agentSocket = null;
    try {
        try {
            // open a socket and send to 
            log.debug("Connected to remote socket");
            InetSocketAddress serverAddress = new InetSocketAddress(host, port);
            agentSocket = new Socket();
            agentSocket.connect(serverAddress, timeoutMillis);

            writer = new PrintWriter(agentSocket.getOutputStream());
            reader = new BufferedReader(new InputStreamReader(agentSocket.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                log.debug("Server message: " + line);
                fromServer += line;
            }
            log.debug("End of server response (=" + fromServer + ")");
        } catch (IOException ex) {
            log.error("Upon connection to and reading server response", ex);
        }
    } finally {
        JavaHelper.safeClose(writer);
        JavaHelper.safeClose(reader);
        JavaHelper.safeClose(agentSocket);
        log.debug("Closed socket connection");
    }

    return fromServer;
}

From source file:org.apache.hadoop.hdfs.client.impl.BlockReaderTestUtil.java

/**
 * Get a BlockReader for the given block.
 *//*from  w  w  w.  j  a va2  s.com*/
public static BlockReader getBlockReader(final DistributedFileSystem fs, LocatedBlock testBlock, int offset,
        long lenToRead) throws IOException {
    InetSocketAddress targetAddr = null;
    ExtendedBlock block = testBlock.getBlock();
    DatanodeInfo[] nodes = testBlock.getLocations();
    targetAddr = NetUtils.createSocketAddr(nodes[0].getXferAddr());

    return new BlockReaderFactory(fs.getClient().getConf()).setInetSocketAddress(targetAddr).setBlock(block)
            .setFileName(targetAddr.toString() + ":" + block.getBlockId())
            .setBlockToken(testBlock.getBlockToken()).setStartOffset(offset).setLength(lenToRead)
            .setVerifyChecksum(true).setClientName("BlockReaderTestUtil").setDatanodeInfo(nodes[0])
            .setClientCacheContext(ClientContext.getFromConf(fs.getConf()))
            .setCachingStrategy(CachingStrategy.newDefaultStrategy()).setConfiguration(fs.getConf())
            .setAllowShortCircuitLocalReads(true).setTracer(FsTracer.get(fs.getConf()))
            .setRemotePeerFactory(new RemotePeerFactory() {
                @Override
                public Peer newConnectedPeer(InetSocketAddress addr, Token<BlockTokenIdentifier> blockToken,
                        DatanodeID datanodeId) throws IOException {
                    Peer peer = null;
                    Socket sock = NetUtils.getDefaultSocketFactory(fs.getConf()).createSocket();
                    try {
                        sock.connect(addr, HdfsConstants.READ_TIMEOUT);
                        sock.setSoTimeout(HdfsConstants.READ_TIMEOUT);
                        peer = DFSUtilClient.peerFromSocket(sock);
                    } finally {
                        if (peer == null) {
                            IOUtils.closeQuietly(sock);
                        }
                    }
                    return peer;
                }
            }).build();
}

From source file:net.grinder.util.NetworkUtil.java

private static InetAddress getAddressWithSocket(String byConnecting, int port) {
    Socket s = null;
    try {/*  w w  w .java 2 s.  c  om*/
        s = new Socket();
        SocketAddress addr = new InetSocketAddress(byConnecting, port);
        s.connect(addr, 2000); // 2 seconds timeout
        return s.getLocalAddress();
    } catch (Exception e) {
        return null;
    } finally {
        IOUtils.closeQuietly(s);
    }
}