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(InetAddress address, int port) throws IOException 

Source Link

Document

Creates a stream socket and connects it to the specified port number at the specified IP address.

Usage

From source file:com.talis.platform.sequencing.zookeeper.ZkTestHelper.java

public boolean waitForServerDown(String hp, long timeout) {
    long start = System.currentTimeMillis();
    String split[] = hp.split(":");
    String host = split[0];//from  w w  w.  jav  a2s  .  c o m
    int port = Integer.parseInt(split[1]);
    while (true) {
        try {
            Socket sock = new Socket(host, port);
            try {
                OutputStream outstream = sock.getOutputStream();
                outstream.write("stat".getBytes());
                outstream.flush();
            } finally {
                sock.close();
            }
        } catch (IOException e) {
            return true;
        }

        if (System.currentTimeMillis() > start + timeout) {
            break;
        }
        try {
            Thread.sleep(250);
        } catch (InterruptedException e) {
            // ignore
        }
    }
    return false;
}

From source file:com.devoteam.srit.xmlloader.http.test.HttpLoaderServer.java

public void testConnection() throws IOException {
    HttpParams params = new BasicHttpParams();
    if (!Clientconn.isOpen()) {
        HttpHost host = new HttpHost(hostname, port);
        Socket socket = new Socket(host.getHostName(), host.getPort());
        Clientconn.bind(socket, params);
    }//from   w w  w  .  j a  v a 2 s .c o m
}

From source file:es.gva.cit.catalog.DiscoveryServiceClient.java

/**
 * It tries if the server is ready//www .j a  va2 s  .c  o  m
 * 
 * @return boolean true --> server is ready false --> server is not ready
 */
public boolean serverIsReady() throws ServerIsNotReadyException {
    Properties systemSettings = System.getProperties();

    Object isProxyEnabled = systemSettings.get("http.proxySet");
    if ((isProxyEnabled == null) || (isProxyEnabled.equals("false"))) {
        Socket sock;
        try {
            sock = new Socket(getUri().getHost(), getUri().getPort());
        } catch (UnknownHostException e) {
            throw new ServerIsNotReadyException(e);
        } catch (IOException e) {
            throw new ServerIsNotReadyException(e);
        }
        return (sock != null);
    } else {
        Object host = systemSettings.get("http.proxyHost");
        Object port = systemSettings.get("http.proxyPort");
        Object user = systemSettings.get("http.proxyUserName");
        Object password = systemSettings.get("http.proxyPassword");
        if ((host != null) && (port != null)) {
            int iPort = 80;
            try {
                iPort = Integer.parseInt((String) port);
            } catch (Exception e) {
                // Use 80
            }
            HttpConnection connection = new HttpConnection(getUri().getHost(), getUri().getPort());
            connection.setProxyHost((String) host);
            connection.setProxyPort(iPort);
            Authenticator.setDefault(new SimpleAuthenticator(user, password));

            try {
                connection.open();
                connection.close();
            } catch (IOException e) {
                throw new ServerIsNotReadyException(e);
            }
        }
    }
    return true;
}

From source file:com.jkoolcloud.tnt4j.streams.plugins.flume.TNT4JStreamsEventSink.java

private void openSocket() throws IOException {
    Utils.close(out);/*from  w ww.java 2s.  c  o m*/
    Utils.close(socket);

    socket = new Socket(hostname, port);
    out = new PrintWriter(socket.getOutputStream(), true);
}

From source file:com.couchbase.client.ClusterManager.java

/**
 * Connects to a given server if a connection has not been made to at least
 * one of the servers in the server list already.
 * @param uri// w  ww. j  a v  a 2s.  co m
 * @return
 */
private boolean connect(URI uri) {
    host = new HttpHost(uri.getHost(), uri.getPort());
    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
    try {
        if (!conn.isOpen()) {
            Socket socket = new Socket(host.getHostName(), host.getPort());
            conn.bind(socket, new SyncBasicHttpParams());
        }
        return true;
    } catch (IOException e) {
        return false;
    }
}

From source file:net.carlh.toast.Client.java

public void start(final String hostName, final int port)
        throws java.net.UnknownHostException, java.io.IOException {

    /* Thread to read stuff from the server */
    readThread = new Thread(new Runnable() {

        private byte[] getData(Socket socket, int length) {
            byte[] d = new byte[length];
            int offset = 0;
            while (offset < length) {
                try {
                    int t = socket.getInputStream().read(d, offset, length - offset);
                    if (t == -1) {
                        break;
                    }/*from w w  w  .j  av  a2  s.  c  o m*/
                    offset += t;
                } catch (SocketException e) {
                    /* This is probably because the socket has been closed in order to make
                       this thread terminate.
                    */
                    Log.e("Toast", "SocketException in client.getData", e);
                    break;
                } catch (IOException e) {
                    Log.e("Toast", "IOException in Client.getData()", e);
                    break;
                }
            }

            return java.util.Arrays.copyOf(d, offset);
        }

        public void run() {
            while (!stop.get()) {
                try {
                    synchronized (mutex) {
                        /* Connect */
                        socket = new Socket(hostName, port);
                        socket.setSoTimeout(timeout);
                    }

                    /* Keep going until there is a problem on read */

                    while (true) {
                        byte[] b = getData(socket, 4);

                        if (b.length != 4) {
                            break;
                        }

                        int length = ((b[0] & 0xff) << 24) | ((b[1] & 0xff) << 16) | ((b[2] & 0xff) << 8)
                                | (b[3] & 0xff);
                        if (length < 0 || length > (256 * 1024)) {
                            /* Don't like the sound of that */
                            Log.e("Toast", "Strange length " + length);
                            break;
                        }

                        byte[] d = getData(socket, length);

                        if (d.length != length) {
                            break;
                        }

                        try {
                            handler(new JSONObject(new String(d)));
                        } catch (JSONException e) {
                            Log.e("Toast", "Exception " + e.toString());
                        }
                    }

                    synchronized (mutex) {
                        /* Close the socket and go back round to connect again */
                        socket.close();
                        socket = null;
                    }

                } catch (ConnectException e) {
                    Log.e("Toast", "ConnectException");
                } catch (UnknownHostException e) {
                    Log.e("Toast", "UnknownHostException");
                } catch (IOException e) {
                    Log.e("Client", "IOException");
                } finally {
                    try {
                        Thread.sleep(timeout);
                    } catch (java.lang.InterruptedException e) {

                    }
                }
            }
        }
    });

    readThread.start();

    /* Thread to send stuff to the server */
    writeThread = new Thread(new Runnable() {

        public void run() {

            while (!stop.get()) {

                lock.lock();
                try {
                    while (toWrite.size() == 0 && !stop.get()) {
                        writeCondition.await();
                    }
                } catch (InterruptedException e) {

                } finally {
                    lock.unlock();
                }

                String s = null;
                lock.lock();
                if (toWrite.size() > 0) {
                    s = toWrite.get(0);
                    toWrite.remove(0);
                }
                lock.unlock();

                synchronized (mutex) {
                    try {
                        if (socket != null && s != null) {
                            socket.getOutputStream().write((s.length() >> 24) & 0xff);
                            socket.getOutputStream().write((s.length() >> 16) & 0xff);
                            socket.getOutputStream().write((s.length() >> 8) & 0xff);
                            socket.getOutputStream().write((s.length() >> 0) & 0xff);
                            socket.getOutputStream().write(s.getBytes());
                        }
                    } catch (IOException e) {
                        Log.e("Toast", "IOException in write");
                    }
                }
            }
        }
    });

    writeThread.start();

    /* Thread to send pings every so often */
    pingThread = new Thread(new Runnable() {
        public void run() {
            while (!stop.get()) {
                if (ping.get() == true && pong.get() == false) {
                    for (Handler h : handlers) {
                        h.sendEmptyMessage(0);
                    }
                    setConnected(false);
                }
                pong.set(false);
                try {
                    JSONObject json = new JSONObject();
                    json.put("type", "ping");
                    send(json);
                    ping.set(true);
                    Thread.sleep(pingInterval);
                } catch (JSONException e) {
                } catch (InterruptedException e) {
                }

            }
        }
    });

    pingThread.start();
}

From source file:client.gui.ConnectionDialog.java

public void actionPerformed(final ActionEvent event) {

    String nick = null;/* w ww.  j  a  v a 2  s .  c o m*/
    String host = null;
    int port = 0;

    if (event.getSource() == connect) {
        nick = this.nick.getText();
        host = this.host.getText();
        try {
            port = Integer.parseInt(this.port.getText());
        } catch (NumberFormatException e1) {
            new MyDialog("Port number must be integer").setVisible(true);
            return;
        }
    } else if (event.getSource() == connectDev) {
        nick = generateNick();
        host = "localhost";
        port = 5555;
    } else if (event.getSource() == connectSame) {
        nick = "a";
        host = "localhost";
        port = 5555;
    }

    if (port <= 0) {
        new MyDialog("Port number must be bigger than 0").setVisible(true);
        return;
    }

    Socket socket;
    BufferedReader in;

    try {
        socket = new Socket(host, port);
        GlobalVariables.out = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    } catch (java.net.UnknownHostException e2) {
        new MyDialog("Unknown host").setVisible(true);
        return;
    } catch (IOException e3) {
        new MyDialog("Connection unsuccessful").setVisible(true);
        GlobalVariables.connected = false;
        return;
    } catch (java.lang.IllegalArgumentException e4) {
        new MyDialog("Port number is too big").setVisible(true);
        return;
    }

    System.out.println("Nick: " + nick);

    final JSONArray toSend = new JSONArray();
    try {
        toSend.put(new JSONObject().put("action", "first_connection"));
        toSend.put(new JSONObject().put("nick", nick));
    } catch (JSONException e1) {
        e1.printStackTrace();
    }

    GlobalVariables.daemon = true;
    GlobalVariables.me.setNick(nick);
    GlobalVariables.connect.setEnabled(false);
    GlobalVariables.connected = true;
    setVisible(false);
    GlobalVariables.out.println(toSend);
    Thread thread;
    thread = new ReceivingData(in);
    thread.setDaemon(true);
    thread.start();
}

From source file:com.nirima.jenkins.SimpleArtifactCopier.java

protected void fetchFile(Artifact art, String path)
        throws IOException, URISyntaxException, UnsupportedEncodingException, UnknownHostException,
        HttpException, TransformerException, SAXException, ParserConfigurationException {

    BasicHttpEntityEnclosingRequest httpget = new BasicHttpEntityEnclosingRequest("GET", path);

    // Start/*from   w w  w. j a  v a 2s .  co  m*/

    if (!conn.isOpen()) {
        Socket socket = new Socket(targetHost.getHostName(),
                targetHost.getPort() > 0 ? targetHost.getPort() : 80);
        conn.bind(socket, params);
    }

    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost);

    httpexecutor.preProcess(httpget, httpproc, context);
    HttpResponse response = httpexecutor.execute(httpget, conn, context);
    httpexecutor.postProcess(response, httpproc, context);

    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        try {

            if (instream != null) {

                File outFile = new File(localRepo, art.getGroupId().replace('.', '/') + "/"
                        + art.getArtifactId() + "/" + art.getVersion());
                outFile.mkdirs();
                outFile = new File(outFile, path.substring(path.lastIndexOf('/') + 1));

                FileOutputStream fos = new FileOutputStream(outFile);
                IOUtils.copy(instream, fos);
                fos.close();

            }

        } catch (IOException ex) {
            conn.shutdown();

        } finally {
            instream.close();
        }
    }
    if (!connStrategy.keepAlive(response, context)) {
        conn.close();
    }

}

From source file:com.zack6849.alphabot.api.Utils.java

public static String checkServerStatus(InetAddress i, int port) {
    String returns = "Error.";
    try {//w  w  w.  j a va2s .c  om
        //wow...i never actually used the port argument?
        Socket s = new Socket(i, port);
        DataInputStream SS_BF = new DataInputStream(s.getInputStream());
        DataOutputStream d = new DataOutputStream(s.getOutputStream());
        d.write(new byte[] { (byte) 0xFE, (byte) 0x01 });
        SS_BF.readByte();
        short length = SS_BF.readShort();
        StringBuilder sb = new StringBuilder();
        for (int in = 0; in < length; in++) {
            char ch = SS_BF.readChar();
            sb.append(ch);
        }
        String all = sb.toString().trim();
        System.out.println(all);
        String[] args1 = all.split("\u0000");
        if (args1[3].contains("")) {
            returns = "MOTD: " + args1[3].replaceAll("[a-m]", "").replaceAll("[1234567890]", "")
                    + "   players: [" + args1[4] + "/" + args1[5] + "]";
        } else {
            returns = "MOTD: " + args1[3] + "   players: [" + args1[4] + "/" + args1[5] + "]";
        }
    } catch (UnknownHostException e1) {
        returns = "the host you specified is unknown. check your settings.";
    } catch (IOException e1) {
        returns = "sorry, we couldn't reach this server, make sure that the server is up and has query enabled.";
    }
    return returns;
}

From source file:matroskastudycoder.HttpControl.java

private void sendGetRequest(String target) {

    try {/*from w w w .  j  ava 2 s .com*/

        //String target = "/requests/status.xml?command=pl_stop";
        //String target = "/requests/status.xml";

        if (!conn.isOpen()) {
            Socket socket = new Socket(host.getHostName(), host.getPort());
            conn.bind(socket, params);
        }
        BasicHttpRequest request = new BasicHttpRequest("GET", target);
        System.out.println(">> Request URI: " + request.getRequestLine().getUri());

        request.setParams(params);
        httpexecutor.preProcess(request, httpproc, context);
        HttpResponse response = httpexecutor.execute(request, conn, context);
        response.setParams(params);
        httpexecutor.postProcess(response, httpproc, context);

        //System.out.println("<< Response: " + response.getStatusLine());
        String responseXML = EntityUtils.toString(response.getEntity());
        //System.out.println(responseXML);
        processRequestResponse(responseXML);
        //System.out.println("==============");

        if (!connStrategy.keepAlive(response, context)) {
            conn.close();
        } else {
            System.out.println("Connection kept alive...");
        }
    } catch (Exception e) {
        System.err.println("error:" + e);
    } finally {
        try {
            conn.close();
        } catch (Exception e) {
            System.err.println("errore:" + e);
        }
    }

}