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) throws IOException 

Source Link

Document

Connects this socket to the server.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    InetAddress addr = InetAddress.getByName("java.sun.com");
    int port = 80;
    SocketAddress sockaddr = new InetSocketAddress(addr, port);

    Socket sock = new Socket();

    sock.connect(sockaddr);
}

From source file:tap.Tap.java

/**
 * Usage:<BR> FIXME?//from w ww. jav  a2 s . com
 *       java votebox.Tap [serial] [report address] [port]
 *
 * @param args      arguments to be used
 *
 * @throws RuntimeException if there is an issue parsing values, the port used is bad,
 *                          or there is an interruption in the process
 */
public static void main(String[] args) {

    IAuditoriumParams params = new AuditoriumParams("tap.conf");

    System.out.println(params.getReportAddress());

    String reportAddr;

    int serial;
    int port;
    String launchCode;

    /* See if there isn't a full argument set */
    if (args.length != 4) {

        int p = 0;

        /* Assign the default serial */
        serial = params.getDefaultSerialNumber();

        /* If the serial is still bad... */
        if (serial == -1) {

            /* Try the first of the given arguments */
            try {
                serial = Integer.parseInt(args[p]);
                p++;
            } catch (Exception e) {
                throw new RuntimeException(
                        "usage: Tap [serial] [report address] [port]\nExpected valid serial.");
            }
        }

        /* Assign the report address */
        reportAddr = params.getReportAddress();

        /* If no valid address... */
        if (reportAddr.length() == 0) {

            /* Try one of the given arguments (first or second, depending) */
            try {
                reportAddr = args[p];
                p++;
            } catch (Exception e) {
                throw new RuntimeException("usage: Tap [serial] [report address] [port]");
            }
        }

        /* Assign the port */
        //port = params.getPort();
        port = Integer.parseInt(args[p]);

        /* If the port is still bad... */
        if (port == -1) {

            /* Try one of the given arguments (first, second, or third, depending) */
            try {
                port = Integer.parseInt(args[p]);
            } catch (Exception e) {
                throw new RuntimeException("usage: Tap [serial] [report address] [port]\nExpected valid port.");
            }
        }

        launchCode = "0000000000";
    }

    /* If there is a full argument set... */
    else {

        /* Try to load up the args */
        try {
            serial = Integer.parseInt(args[0]);
            reportAddr = args[1];
            port = Integer.parseInt(args[2]);
            launchCode = args[3];
        } catch (Exception e) {
            throw new RuntimeException("usage: Tap [serial] [report address] [port]");
        }
    }

    try {

        /* Create a new socket address */
        System.out.println(reportAddr + port);
        InetSocketAddress addr = new InetSocketAddress(reportAddr, port);

        /* Loop until an exception or tap is started */
        while (true) {

            try {

                /* Try to establish a socket connection */
                Socket localCon = new Socket();
                localCon.connect(addr);

                /* Start the tap */
                (new Tap(serial, localCon.getOutputStream(), launchCode, params)).start();
                System.out.println("Connection successful to " + addr);
                break;
            } catch (IOException e) { /* If no good, retry */
                System.out.println("Connection failed: " + e.getMessage());
                System.out.println("Retry in 5 seconds...");
                Thread.sleep(5000);
            }
        }
    } catch (NumberFormatException e) {
        throw new RuntimeException(
                "usage: Tap [serial] [report address] [port]; where port is between 1 and 65335 & [serial] is a positive integer",
                e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }

    /* TEST CODE */

    testMethod();

    /* END TEST CODE */

}

From source file:org.devtcg.five.server.UPnPService.java

/**
 * Determine the source IP (our IP) of our route to www.google.com:80. If
 * the user has layers of indirection to access the Internet, it is our
 * assumption that this function will return an address in the RFC1918
 * private space; otherwise, no IGD mappings are necessary.
 *
 * @throws IOException/*from w w  w . java 2  s . c o  m*/
 */
private static InetAddress determineDefaultRouteLocalAddress() throws IOException {
    Socket socket = new Socket();
    try {
        socket.connect(new InetSocketAddress("www.google.com", 80));
        return socket.getLocalAddress();
    } finally {
        socket.close();
    }
}

From source file:gridool.util.xfer.TransferUtils.java

public static void send(@Nonnull final FastByteArrayOutputStream data, @Nonnull final String fileName,
        @Nullable final String writeDirPath, @Nonnull final InetAddress dstAddr, final int dstPort,
        final boolean append, final boolean sync, @Nullable final TransferClientHandler handler)
        throws IOException {
    final SocketAddress dstSockAddr = new InetSocketAddress(dstAddr, dstPort);
    SocketChannel channel = null;
    Socket socket = null;
    final OutputStream out;
    try {//  w w  w .j a v  a  2 s.  com
        channel = SocketChannel.open();
        socket = channel.socket();
        socket.connect(dstSockAddr);
        out = socket.getOutputStream();
    } catch (IOException e) {
        LOG.error("failed to connect: " + dstSockAddr, e);
        IOUtils.closeQuietly(channel);
        NetUtils.closeQuietly(socket);
        throw e;
    }

    DataInputStream din = null;
    if (sync) {
        InputStream in = socket.getInputStream();
        din = new DataInputStream(in);
    }
    final DataOutputStream dos = new DataOutputStream(out);
    final StopWatch sw = new StopWatch();
    try {
        IOUtils.writeString(fileName, dos);
        IOUtils.writeString(writeDirPath, dos);
        long nbytes = data.size();
        dos.writeLong(nbytes);
        dos.writeBoolean(append);
        dos.writeBoolean(sync);
        if (handler == null) {
            dos.writeBoolean(false);
        } else {
            dos.writeBoolean(true);
            handler.writeAdditionalHeader(dos);
        }

        // send file using zero-copy send
        data.writeTo(out);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Sent a file data '" + fileName + "' of " + nbytes + " bytes to " + dstSockAddr.toString()
                    + " in " + sw.toString());
        }

        if (sync) {// receive ack in sync mode
            long remoteRecieved = din.readLong();
            if (remoteRecieved != nbytes) {
                throw new IllegalStateException(
                        "Sent " + nbytes + " bytes, but remote node received " + remoteRecieved + " bytes");
            }
        }
    } catch (FileNotFoundException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw e;
    } catch (IOException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw e;
    } finally {
        IOUtils.closeQuietly(din, dos);
        IOUtils.closeQuietly(channel);
        NetUtils.closeQuietly(socket);
    }
}

From source file:gridool.util.xfer.TransferUtils.java

public static void sendfile(@Nonnull final File file, final long fromPos, final long count,
        @Nullable final String writeDirPath, @Nonnull final InetAddress dstAddr, final int dstPort,
        final boolean append, final boolean sync, @Nonnull final TransferClientHandler handler)
        throws IOException {
    if (!file.exists()) {
        throw new IllegalArgumentException(file.getAbsolutePath() + " does not exist");
    }//from   w  ww  . ja  va2  s .co m
    if (!file.isFile()) {
        throw new IllegalArgumentException(file.getAbsolutePath() + " is not file");
    }
    if (!file.canRead()) {
        throw new IllegalArgumentException(file.getAbsolutePath() + " cannot read");
    }

    final SocketAddress dstSockAddr = new InetSocketAddress(dstAddr, dstPort);
    SocketChannel channel = null;
    Socket socket = null;
    final OutputStream out;
    try {
        channel = SocketChannel.open();
        socket = channel.socket();
        socket.connect(dstSockAddr);
        out = socket.getOutputStream();
    } catch (IOException e) {
        LOG.error("failed to connect: " + dstSockAddr, e);
        IOUtils.closeQuietly(channel);
        NetUtils.closeQuietly(socket);
        throw e;
    }

    DataInputStream din = null;
    if (sync) {
        InputStream in = socket.getInputStream();
        din = new DataInputStream(in);
    }
    final DataOutputStream dos = new DataOutputStream(out);
    final StopWatch sw = new StopWatch();
    FileInputStream src = null;
    final long nbytes;
    try {
        src = new FileInputStream(file);
        FileChannel fc = src.getChannel();

        String fileName = file.getName();
        IOUtils.writeString(fileName, dos);
        IOUtils.writeString(writeDirPath, dos);
        long xferBytes = (count == -1L) ? fc.size() : count;
        dos.writeLong(xferBytes);
        dos.writeBoolean(append); // append=false
        dos.writeBoolean(sync);
        if (handler == null) {
            dos.writeBoolean(false);
        } else {
            dos.writeBoolean(true);
            handler.writeAdditionalHeader(dos);
        }

        // send file using zero-copy send
        nbytes = fc.transferTo(fromPos, xferBytes, channel);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Sent a file '" + file.getAbsolutePath() + "' of " + nbytes + " bytes to "
                    + dstSockAddr.toString() + " in " + sw.toString());
        }

        if (sync) {// receive ack in sync mode
            long remoteRecieved = din.readLong();
            if (remoteRecieved != xferBytes) {
                throw new IllegalStateException(
                        "Sent " + xferBytes + " bytes, but remote node received " + remoteRecieved + " bytes");
            }
        }

    } catch (FileNotFoundException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw e;
    } catch (IOException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw e;
    } finally {
        IOUtils.closeQuietly(src);
        IOUtils.closeQuietly(din, dos);
        IOUtils.closeQuietly(channel);
        NetUtils.closeQuietly(socket);
    }
}

From source file:org.apache.blur.console.util.NodeUtil.java

public static Map<String, Object> getZookeeperStatus() throws IOException {
    String[] connections = Config.getBlurConfig().get("blur.zookeeper.connection").split(",");
    Set<String> onlineZookeepers = new HashSet<String>();
    Set<String> offlineZookeepers = new HashSet<String>();

    for (String connection : connections) {
        Socket socket = null;
        InputStream response = null;
        OutputStream question = null;
        try {/*from  w  ww . ja va2s  .  c  o m*/
            URI parsedConnection = new URI("my://" + connection);
            String host = parsedConnection.getHost();
            int port = parsedConnection.getPort() >= 0 ? parsedConnection.getPort() : 2181;
            byte[] reqBytes = new byte[4];
            ByteBuffer req = ByteBuffer.wrap(reqBytes);
            req.putInt(ByteBuffer.wrap("ruok".getBytes()).getInt());
            socket = new Socket();
            socket.setSoLinger(false, 10);
            socket.setSoTimeout(20000);
            parsedConnection.getPort();
            socket.connect(new InetSocketAddress(host, port));

            response = socket.getInputStream();
            question = socket.getOutputStream();

            question.write(reqBytes);

            byte[] resBytes = new byte[4];

            response.read(resBytes);
            String status = new String(resBytes);
            if (status.equals("imok")) {
                onlineZookeepers.add(connection);
            } else {
                offlineZookeepers.add(connection);
            }
            socket.close();
            response.close();
            question.close();
        } catch (Exception e) {
            offlineZookeepers.add(connection);
        } finally {
            if (socket != null) {
                socket.close();
            }
            if (response != null) {
                response.close();
            }
            if (question != null) {
                question.close();
            }
        }
    }

    Map<String, Object> data = new HashMap<String, Object>();

    data.put("online", onlineZookeepers);
    data.put("offline", offlineZookeepers);

    return data;
}

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);
    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();/*ww w.j a  v a  2  s .  c  om*/
    server.shutdown();
}

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

public void testInvalidHandshake() throws IOException, JSONException, InterruptedException {
    JsonRpcServer server = new JsonRpcServer(null, "foo");
    InetSocketAddress address = server.startLocal(0);
    Socket client = new Socket();
    client.connect(address);
    PrintStream out = new PrintStream(client.getOutputStream());
    out.println(buildRequest(0, "_authenticate", Lists.newArrayList("bar")));
    BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    JSONObject response = new JSONObject(in.readLine());
    Object error = response.get("error");
    assertTrue(JSONObject.NULL != error);
    while (!out.checkError()) {
        out.println(buildRequest(0, "makeToast", Lists.newArrayList("baz")));
    }//from w w w  .ja v a 2  s  .  c o m
    client.close();
    // Further connections should fail;
    client = new Socket();
    try {
        client.connect(address);
        fail();
    } catch (IOException e) {
    }
}

From source file:org.cloudifysource.mongodb.MongoLivenessDetector.java

@Override
public EventResult onPreStart(StartReason reason) {
    if (!initialized)
        init();//from ww  w  .ja  v  a  2s .  c o m
    Socket sock = new Socket();
    try {
        sock.connect(new InetSocketAddress(host, port));
        sock.close();
        throw new IllegalStateException("The Port Liveness Detector found that port " + port
                + " is IN USE before the process was launched!");
    } catch (IOException e) {
        log.debug("The Port Liveness Detector found that the port " + port
                + " is FREE and can be used by the process");
    } finally {
        try {
            sock.close();
        } catch (IOException e) {
            // ignore
        }
    }
    return EventResult.SUCCESS;
}

From source file:org.conqat.engine.bugzilla.lib.SimpleSSLSocketFactory.java

/** {@inheritDoc} */
@Override/*from  w w  w . j  a  v a  2  s  .  c o  m*/
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
    // work-around for bug in Java 7 (see
    // http://stackoverflow.com/questions/7615645/ssl-handshake-alert-unrecognized-name-error-since-upgrade-to-java-1-7-0
    // and http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7127374 for
    // details)
    Socket socket = sc.getSocketFactory().createSocket();
    socket.connect(new InetSocketAddress(host, port));
    return socket;
}