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:ca.farrelltonsolar.classic.PVOutputUploader.java

private Socket Connect(String hostname) throws InterruptedException {
    final Socket mySocket = new Socket();
    do {// w w  w .  ja va 2s.c  om
        try {
            InetAddress ipaddress = InetAddress.getByName(hostname);
            SocketAddress address = new InetSocketAddress(ipaddress, 80);
            mySocket.connect(address, 3500);
        } catch (IOException ex) {
            Log.w(getClass().getName(),
                    String.format("PVOutput trying to connect to %s, failed ex: %s", hostname, ex));
            Thread.sleep(2 * 60000);
        }
    } while (mySocket.isConnected() == false);
    return mySocket;
}

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

public void run() {
    try {//w ww  .j  a va  2  s.  c om
        String line1 = input.readLine();
        switch (line1) {
        case "101 ping":
            ch_log.i("Client pinged us, responding with an acknowledgement.");
            output.write("102 pong");
            output.newLine();
            output.flush();
            output.close();
            break;
        case "302 request key update":
            ch_log.i("Client is requesting a key update.");
            KeyUpdate update = new KeyUpdate(ip);
            KeyUpdateManager.addPendingUpdate(connection_id, update);
            while (KeyUpdateManager.getUpdate(connection_id).isProcessed()) {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            boolean accepted = KeyUpdateManager.getUpdate(connection_id).isAccepted();
            KeyUpdateManager.completeIncomingUpdate(connection_id, KeyUpdateManager.getUpdate(connection_id));
            if (accepted) {
                ch_log.i("Accepting key update");
                try {
                    output.write("303 update");
                    output.newLine();
                    output.flush();

                    String pubkeyB64 = input.readLine();

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

                    output.close();
                    input.close();

                    KeyManager.saveKeyByIP(ip, keyFactory.generatePublic(pubSpec));
                } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
                    ch_log.e("Error updating sender's key!");
                    e.printStackTrace();
                }
            } else {
                ch_log.i("Rejecting key update.");
                output.write("304 no update");
                output.newLine();
                output.flush();
                output.close();
            }
            break;
        case "301 getkey":
            ch_log.i("Client requested our public key, sending.");
            String pubkeyB64 = Base64.encodeBase64String(Main.getKeypair().getPublic().getEncoded());
            output.write(pubkeyB64);
            output.newLine();
            output.flush();
            output.close();
            break;
        case "200 encrypted message": //incoming encrypted message
            ch_log.i("Client sent an encrypted message, attempting verification and decryption.");
            PrivateKey privkey = Main.getKeypair().getPrivate();
            String cryptedMsg = input.readLine() + "\n" + input.readLine() + "\n" + input.readLine();

            ch_log.i("Checking for sender's public key.");
            if (KeyManager.checkIfIPKeyExists(ip)) {
                ch_log.i("Public key found.");
            } else {
                ch_log.i("Public key not found, requesting key from their server.");
                try {
                    Socket socketGetkey = new Socket();
                    socketGetkey.connect(new InetSocketAddress(InetAddress.getByName(ip), 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 sender_pubkeyB64 = inputGetkey.readLine();
                    byte[] pubEncoded = Base64.decodeBase64(sender_pubkeyB64);
                    X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubEncoded);
                    KeyFactory keyFactory = KeyFactory.getInstance("RSA");

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

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

            PacchatMessage message = MsgCrypto.decryptAndVerifyMessage(cryptedMsg, privkey,
                    KeyManager.loadKeyByIP(ip));

            String msg = message.getMessage();
            boolean verified = message.isVerified();
            boolean decrypted = message.isDecryptedSuccessfully();

            String ANSI_RESET = "\u001B[0m";
            String ANSI_CYAN = "\u001B[36m";
            String ANSI_BOLD = "\u001B[1m";
            if (verified && decrypted) {
                ch_log.i("Acknowledging message.");
                output.write("201 message acknowledgement");
                output.newLine();
                output.flush();
                output.close();
                System.out.println(ANSI_BOLD + ANSI_CYAN + "-----BEGIN MESSAGE-----" + ANSI_RESET);
                System.out.println(ANSI_BOLD + ANSI_CYAN + msg + ANSI_RESET);
                System.out.println(ANSI_BOLD + ANSI_CYAN + "-----END MESSAGE-----" + ANSI_RESET);
            } else if (!verified && decrypted) {
                ch_log.w("Notifying client that message authenticity was not verified.");
                output.write("203 unable to verify");
                output.newLine();
                output.flush();
                output.close();
                System.out.println(ANSI_BOLD + ANSI_CYAN + "-----BEGIN MESSAGE-----" + ANSI_RESET);
                System.out.println(ANSI_BOLD + ANSI_CYAN + msg + ANSI_RESET);
                System.out.println(ANSI_BOLD + ANSI_CYAN + "-----END MESSAGE-----" + ANSI_RESET);
            } else if (!verified) {
                ch_log.w("Notifying client that message could not be decrypted.");
                output.write("202 unable to decrypt");
                output.newLine();
                output.flush();
                output.close();
            }
            break;
        case "201 message acknowledgement":
            ch_log.i("Client sent an invalid message acknowledgement.");
            output.write("400 invalid transmission header");
            output.newLine();
            output.flush();
            output.close();
        case "202 unable to decrypt":
            ch_log.i("Client sent an invalid 'unable to decrypt' transmission.");
            output.write("400 invalid transmission header");
            output.newLine();
            output.flush();
            output.close();
        case "203 unable to verify":
            ch_log.i("Client sent an invalid 'unable to verify' transmission.");
            output.write("400 invalid transmission header");
            output.newLine();
            output.flush();
            output.close();
        default:
            ch_log.i("Client sent an invalid request header: " + line1);
            output.write("400 invalid transmission header");
            output.newLine();
            output.flush();
            output.close();
            break;
        }
    } catch (IOException e) {
        ch_log.e("Error in connection handler " + connection_id);
        e.printStackTrace();
    }
}

From source file:org.csploit.android.core.System.java

public static boolean isPortAvailable(int port) {
    boolean available = true;

    int available_code = mOpenPorts.get(port);

    if (available_code != 0)
        return available_code != 1;

    try {/*from  w w w.ja  v  a2s . c om*/
        // attempt 3 times since proxy and server could be still releasing
        // their ports
        for (int i = 0; i < 3; i++) {
            Socket channel = new Socket();
            InetSocketAddress address = new InetSocketAddress(
                    InetAddress.getByName(mNetwork.getLocalAddressAsString()), port);

            channel.connect(address, 200);

            available = !channel.isConnected();

            channel.close();

            if (available)
                break;

            Thread.sleep(200);
        }
    } catch (Exception e) {
        available = true;
    }

    mOpenPorts.put(port, available ? 2 : 1);

    return available;
}

From source file:org.devproof.portal.core.module.common.util.httpclient.ssl.EasySSLProtocolSocketFactory.java

/**
 * Attempts to get a new socket connection to the given host within the
 * given time limit.//from w  w w.  j a  v  a 2 s . co  m
 * <p>
 * To circumvent the limitations of older JREs that do not support connect
 * timeout a controller thread is executed. The controller thread attempts
 * to create a new socket within the given limit of time. If socket
 * constructor does not return until the timeout expires, the controller
 * terminates and throws an {@link ConnectTimeoutException}
 * </p>
 *
 * @param host         the host name/IP
 * @param port         the port on the host
 * @param localAddress the local host name/IP to bind the socket to
 * @param localPort    the port on the local machine
 * @param params       {@link HttpConnectionParams Http connection parameters}
 * @return Socket a new socket
 * @throws IOException          if an I/O error occurs while creating the socket
 * @throws UnknownHostException if the IP address of the host cannot be determined
 */
public Socket createSocket(String host, int port, InetAddress localAddress, int localPort,
        HttpConnectionParams params) throws IOException {
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }
    int timeout = params.getConnectionTimeout();
    SocketFactory socketfactory = getSSLContext().getSocketFactory();
    if (timeout == 0) {
        return socketfactory.createSocket(host, port, localAddress, localPort);
    } else {
        Socket socket = socketfactory.createSocket();
        SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
        SocketAddress remoteaddr = new InetSocketAddress(host, port);
        socket.bind(localaddr);
        socket.connect(remoteaddr, timeout);
        return socket;
    }
}

From source file:in.mycp.remote.InfraService.java

public String getInfraStatus(Infra infra) {
    String status = Commons.EUCA_STATUS.unknown + "";
    try {/*from   w  w w  .ja  v a 2  s. c  om*/
        //first , just try to reach and ping the server, then try connecting
        try {
            InetAddress byIpAsName = InetAddress.getByName(infra.getServer());
            SocketAddress sockaddr = new InetSocketAddress(byIpAsName, infra.getPort());
            Socket theSock = new Socket();
            theSock.connect(sockaddr, 2000);
        } catch (Exception e) {
            //log.error(e.getMessage());//e.printStackTrace();
            log.info(e.getMessage());
            status = Commons.EUCA_STATUS.unreachable + "";
            throw new Exception(
                    "Cant even open socket to server " + infra.getServer() + ".wont try to connect!");
        }

        BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
        textEncryptor.setPassword("gothilla");
        String decAccessId = textEncryptor.decrypt(infra.getAccessId());
        String decSecretKey = textEncryptor.decrypt(infra.getSecretKey());

        Jec2 ec2 = new Jec2(decAccessId, decSecretKey, false, infra.getServer(), infra.getPort());
        ec2.setResourcePrefix(infra.getResourcePrefix());
        ec2.setSignatureVersion(infra.getSignatureVersion());
        ec2.setMaxRetries(1);
        List params = new ArrayList<String>();
        List<RegionInfo> regions = ec2.describeRegions(params);
        for (Iterator iterator = regions.iterator(); iterator.hasNext();) {
            RegionInfo regionInfo = (RegionInfo) iterator.next();
            if (regionInfo != null) {
                status = Commons.EUCA_STATUS.running + "";
            } else if (regionInfo == null) {
                status = Commons.EUCA_STATUS.unknown + "";
            }
            break;
        }
    } catch (Exception e) {
        log.error(e.getMessage());//e.printStackTrace();
        status = Commons.EUCA_STATUS.unknown + "";
    }
    //System.out.println(" = ssssssssssssssssssssssssssssssss ");
    return status;
}

From source file:org.eclipse.mylyn.internal.commons.repositories.http.core.PollingSslProtocolSocketFactory.java

public Socket connectSocket(Socket sock, InetSocketAddress remoteAddress, InetSocketAddress localAddress,
        HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    Assert.isNotNull(params);//w  w  w.j  ava 2  s  . com
    final Socket socket = (sock != null) ? sock : createSocket(params);

    if (localAddress != null) {
        socket.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
        socket.bind(localAddress);
    }

    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    socket.connect(remoteAddress, connTimeout);

    if (socket instanceof SSLSocket) {
        return socket;
    } else {
        return getSslSupport(params).getSocketFactory().createSocket(socket, remoteAddress.getHostName(),
                remoteAddress.getPort(), true);
    }
}

From source file:org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory.java

/**
 * Attempts to get a new socket connection to the given host within the given time limit.
 * <p>//www .ja va  2s . c  o m
 * To circumvent the limitations of older JREs that do not support connect timeout a 
 * controller thread is executed. The controller thread attempts to create a new socket 
 * within the given limit of time. If socket constructor does not return until the 
 * timeout expires, the controller terminates and throws an {@link ConnectTimeoutException}
 * </p>
 *  
 * @param host the host name/IP
 * @param port the port on the host
 * @param clientHost the local host name/IP to bind the socket to
 * @param clientPort the port on the local machine
 * @param params {@link HttpConnectionParams Http connection parameters}
 * 
 * @return Socket a new socket
 * 
 * @throws IOException if an I/O error occurs while creating the socket
 * @throws UnknownHostException if the IP address of the host cannot be
 * determined
 */
public Socket createSocket(final String host, final int port, final InetAddress localAddress,
        final int localPort, final HttpParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }
    int timeout = HttpConnectionParams.getConnectionTimeout(params);
    ;
    SocketFactory socketfactory = getSSLContext().getSocketFactory();
    if (timeout == 0) {
        return socketfactory.createSocket(host, port, localAddress, localPort);
    } else {
        Socket socket = socketfactory.createSocket();
        SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
        SocketAddress remoteaddr = new InetSocketAddress(host, port);
        socket.bind(localaddr);
        socket.connect(remoteaddr, timeout);
        return socket;
    }
}

From source file:br.com.ararati.operacoes.SocketFactory.java

@Override
public Socket createSocket(String host, int port, InetAddress localAddress, int localPort,
        HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    if (params == null) {
        throw new IllegalArgumentException("HttpConnectionParams: Parmetros no podem ser nulos.");
    }// ww w  .  j a v  a  2 s . c om

    int timeout = params.getConnectionTimeout();
    javax.net.SocketFactory socketfactory = getSSLContext().getSocketFactory();
    if (timeout == 0) {
        return socketfactory.createSocket(host, port, localAddress, localPort);
    }

    Socket socket = socketfactory.createSocket();
    SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
    SocketAddress remoteaddr = new InetSocketAddress(host, port);
    socket.bind(localaddr);
    try {
        socket.connect(remoteaddr, timeout);
    } catch (Exception e) {
        error(e.toString());
        throw new ConnectTimeoutException("Possvel timeout de conexo", e);
    }

    return socket;
}

From source file:com.neophob.sematrix.listener.TcpServer.java

/**
 * Connect to client./*from  ww w  .j ava 2 s. c  o  m*/
 */
private void connectToClient() {
    Socket socket = new Socket();
    lastConnectTimestamp = System.currentTimeMillis();
    try {
        socket.connect(new InetSocketAddress(sendHost, sendPort), 2000);
        client = new Client(app, socket);
        LOG.log(Level.INFO, "Pure Data Client connected at " + sendHost + ":" + sendPort + "!");
        pdClientConnected = true;
    } catch (Exception e) {
        LOG.log(Level.WARNING, "Pure Data Client not found at " + sendHost + ":" + sendPort);
        pdClientConnected = false;
        client = null;
        if (socket != null) {
            try {
                socket.close();
            } catch (Exception e2) {
            }
        }
    }
}

From source file:com.force.api.systest.EasySSLProtocolSocketFactory.java

/**
 * Attempts to get a new socket connection to the given host within the given time limit.
 * <p>/*from w ww .  j  a v  a2s  . c  om*/
 * To circumvent the limitations of older JREs that do not support connect timeout a 
 * controller thread is executed. The controller thread attempts to create a new socket 
 * within the given limit of time. If socket constructor does not return until the 
 * timeout expires, the controller terminates and throws an {@link ConnectTimeoutException}
 * </p>
 *  
 * @param host the host name/IP
 * @param port the port on the host
 * @param clientHost the local host name/IP to bind the socket to
 * @param clientPort the port on the local machine
 * @param params {@link HttpConnectionParams Http connection parameters}
 * 
 * @return Socket a new socket
 * 
 * @throws IOException if an I/O error occurs while creating the socket
 * @throws UnknownHostException if the IP address of the host cannot be
 * determined
 */
@Override
public Socket createSocket(final String host, final int port, final InetAddress localAddress,
        final int localPort, final HttpConnectionParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }
    int timeout = params.getConnectionTimeout();
    SocketFactory socketfactory = getSSLContext().getSocketFactory();
    if (timeout == 0) {
        return socketfactory.createSocket(host, port, localAddress, localPort);
    } else {
        Socket socket = socketfactory.createSocket();
        SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
        SocketAddress remoteaddr = new InetSocketAddress(host, port);
        socket.bind(localaddr);
        socket.connect(remoteaddr, timeout);
        return socket;
    }
}