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.adaptris.core.stubs.ExternalResourcesHelper.java

public static boolean isExternalServerAvailable(String server, int port) {
    boolean result = false;
    try (Socket s = new Socket()) {
        // Try and get a socket to dev on port 80
        // don't give it more than a second though...
        InetSocketAddress addr = new InetSocketAddress(InetAddress.getByName(server), port);
        s.connect(addr, 1000);//from  w  ww . j  a  va  2  s.  co  m
        result = true;
    } catch (Exception e) {
    }
    return result;
}

From source file:com.mirth.connect.server.util.ConnectorUtil.java

public static ConnectionTestResponse testConnection(String host, int port, int timeout, String localAddr,
        int localPort) throws Exception {
    Socket socket = null;/*www . j  a  v a  2 s.  c  o  m*/
    InetSocketAddress address = null;
    InetSocketAddress localAddress = null;

    try {
        address = new InetSocketAddress(host, port);

        if (StringUtils.isBlank(address.getAddress().getHostAddress()) || (address.getPort() < 0)
                || (address.getPort() > 65534)) {
            throw new Exception();
        }
    } catch (Exception e) {
        return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE, "Invalid host or port.");
    }

    if (localAddr != null) {
        try {
            localAddress = new InetSocketAddress(localAddr, localPort);

            if (StringUtils.isBlank(localAddress.getAddress().getHostAddress()) || (localAddress.getPort() < 0)
                    || (localAddress.getPort() > 65534)) {
                throw new Exception();
            }
        } catch (Exception e) {
            return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE,
                    "Invalid local host or port.");
        }
    }

    try {
        socket = new Socket();

        if (localAddress != null) {
            try {
                socket.bind(localAddress);
            } catch (Exception e) {
                return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE,
                        "Could not bind to local address: " + localAddress.getAddress().getHostAddress() + ":"
                                + localAddress.getPort());
            }
        }

        socket.connect(address, timeout);
        String connectionInfo = socket.getLocalAddress().getHostAddress() + ":" + socket.getLocalPort() + " -> "
                + address.getAddress().getHostAddress() + ":" + address.getPort();
        return new ConnectionTestResponse(ConnectionTestResponse.Type.SUCCESS,
                "Successfully connected to host: " + connectionInfo, connectionInfo);
    } catch (SocketTimeoutException ste) {
        return new ConnectionTestResponse(ConnectionTestResponse.Type.TIME_OUT, "Timed out connecting to host: "
                + address.getAddress().getHostAddress() + ":" + address.getPort());
    } catch (Exception e) {
        return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE, "Could not connect to host: "
                + address.getAddress().getHostAddress() + ":" + address.getPort());
    } finally {
        if (socket != null) {
            socket.close();
        }
    }
}

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;/*from w w w .  j ava  2  s  . com*/
    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:com.zextras.zimbradrive.statustest.ConnectionTestUtils.java

public boolean pingHost(URL url, int connectionTimeout) throws MalformedURLException {
    String host = url.getHost();//from  w w w. j ava 2  s . c  om
    int port = url.getPort();
    if (port == -1) {
        if (url.getProtocol().equals("https")) {
            port = 443;
        } else {
            port = 80;
        }
    }
    try (Socket socket = new Socket()) {
        InetSocketAddress inetSocketAddress = new InetSocketAddress(host, port);
        socket.connect(inetSocketAddress, connectionTimeout);
        return true;
    } catch (IOException e) {
        return false; // Either timeout or unreachable or failed DNS lookup.
    }
}

From source file:org.opensaml.security.httpclient.impl.MockTLSSocketFactory.java

public MockTLSSocketFactory() {
    socket = new Socket();
}

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

public void run() {
    Socket socket;// ww  w .  j  av a 2s.c o  m
    BufferedReader input;
    BufferedWriter output;

    kuc_log.i("Connecting to server at " + server_ip);

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

    try {
        kuc_log.i("Requesting a key update.");
        output.write("302 request key update");
        output.newLine();
        output.flush();

        kuc_log.i("Awaiting response from server.");
        String update = input.readLine();
        switch (update) {
        case "303 update":
            kuc_log.i("Server accepted update request, sending public key.");
            String pubkeyB64 = Base64.encodeBase64String(Main.getKeypair().getPublic().getEncoded());
            output.write(pubkeyB64);
            output.newLine();
            output.flush();
            output.close();
            break;
        case "304 no update":
            kuc_log.i("Server rejected update request, closing connection.");
            input.close();
            output.close();
            break;
        case "305 update unavailable":
            kuc_log.i("Server cannot update at this time, try again later.");
            input.close();
            output.close();
            break;
        default:
            kuc_log.i("Server sent back invalid response");
            input.close();
            output.close();
            break;
        }
    } catch (IOException e) {
        kuc_log.e("Error in key update request!");
        e.printStackTrace();
    }
}

From source file:gridool.util.net.SocketUtils.java

public static Socket openSocket(SocketAddress sockAddr, int connectTimeout, long pollDelay, int maxRetry)
        throws IOException {
    Socket socket = new Socket();
    return openSocket(socket, sockAddr, connectTimeout, pollDelay, maxRetry);
}

From source file:com.googlecode.android_scripting.jsonrpc.JsonRpcServerTest.java

public void testValidHandshake() throws IOException, JSONException {
    JsonRpcServer server = new JsonRpcServer(null, "foo");
    InetSocketAddress address = server.startLocal(0);
    Socket client = new Socket();
    client.connect(address);//from   w w  w .  jav a 2  s  . c  o m
    PrintStream out = new PrintStream(client.getOutputStream());
    out.println(buildRequest(0, "_authenticate", Lists.newArrayList("foo")));
    BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    JSONObject response = new JSONObject(in.readLine());
    Object error = response.get("error");
    assertEquals(JSONObject.NULL, error);
    client.close();
    server.shutdown();
}

From source file:com.smartwork.client.gsocket.CommonSocketFactory.java

public Object makeObject(Object key) throws Exception {
    ServerAddress address = (ServerAddress) key;
    Socket conn = new Socket();
    conn.setSoTimeout(networkConfig.getReadTimeout() * 1000);
    conn.setTcpNoDelay(networkConfig.isTcpNoDelay());
    conn.setReuseAddress(networkConfig.isReuseAddress());
    conn.setSoLinger(networkConfig.getSoLinger() > 0, networkConfig.getSoLinger());
    conn.setSendBufferSize(networkConfig.getSendBufferSize());
    conn.setReceiveBufferSize(networkConfig.getReceiveBufferSize());
    conn.connect(new InetSocketAddress(address.getHost(), address.getPort()),
            networkConfig.getConnectTimeout() * 1000);
    return conn;//from  ww w  .  ja v  a  2  s. com
}

From source file:example.springdata.redis.test.util.RequiresRedisServer.java

@Override
protected void before() throws Throwable {

    try (Socket socket = new Socket()) {
        socket.setTcpNoDelay(true);//w ww .ja  va 2s . co  m
        socket.setSoLinger(true, 0);
        socket.connect(new InetSocketAddress(host, port), timeout);
    } catch (Exception e) {
        throw new AssumptionViolatedException(
                String.format("Seems as redis is not running at %s:%s.", host, port), e);
    }
}