Example usage for java.net Socket getInputStream

List of usage examples for java.net Socket getInputStream

Introduction

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

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream for this socket.

Usage

From source file:com.zhch.example.commons.http.v4_5.ProxyTunnelDemo.java

/**
 * ?? demo/*from  w  w  w .j  ava  2s.  co  m*/
 * 
 * @throws Exception
 */
public final static void officalDemo() throws Exception {
    ProxyClient proxyClient = new ProxyClient();
    HttpHost target = new HttpHost("www.yahoo.com", 80);
    HttpHost proxy = new HttpHost("localhost", 8888);
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user", "pwd");
    Socket socket = proxyClient.tunnel(proxy, target, credentials);
    try {
        Writer out = new OutputStreamWriter(socket.getOutputStream(), HTTP.DEF_CONTENT_CHARSET);
        out.write("GET / HTTP/1.1\r\n");
        out.write("Host: " + target.toHostString() + "\r\n");
        out.write("Agent: whatever\r\n");
        out.write("Connection: close\r\n");
        out.write("\r\n");
        out.flush();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(socket.getInputStream(), HTTP.DEF_CONTENT_CHARSET));
        String line = null;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }
    } finally {
        socket.close();
    }
}

From source file:com.liveramp.hank.test.ZkTestCase.java

private static boolean waitForServerUp(int port, long timeout) {
    long start = System.currentTimeMillis();
    while (true) {
        try {//from w w  w. ja  v  a 2s. c om
            Socket sock = new Socket("localhost", port);
            BufferedReader reader = null;
            try {
                OutputStream outstream = sock.getOutputStream();
                outstream.write("stat".getBytes());
                outstream.flush();

                Reader isr = new InputStreamReader(sock.getInputStream());
                reader = new BufferedReader(isr);
                String line = reader.readLine();
                if (line != null && line.startsWith("Zookeeper version:")) {
                    return true;
                }
            } finally {
                sock.close();
                if (reader != null) {
                    reader.close();
                }
            }
        } catch (IOException e) {
            // ignore as this is expected
            LOG.info("server localhost:" + port + " not up " + e);
        }

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

From source file:uk.ac.bbsrc.tgac.miso.integration.util.IntegrationUtils.java

/**
 * Sends a String message to a given host socket
 * //from ww  w.  j  a v  a 2 s . c o  m
 * @param socket
 *          of type Socket
 * @param query
 *          of type String
 * @return String
 * @throws IntegrationException
 *           when the socket couldn't be created
 */
public static String sendMessage(Socket socket, String query) throws IntegrationException {
    BufferedWriter wr = null;
    BufferedReader rd = null;
    try {
        wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));

        // Send data
        wr.write(query + "\r\n");
        wr.flush();

        // Get response
        rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        wr.close();
        rd.close();

        String dirty = sb.toString();
        StringBuilder response = new StringBuilder();
        int codePoint;
        int i = 0;
        while (i < dirty.length()) {
            codePoint = dirty.codePointAt(i);
            if ((codePoint == 0x9) || (codePoint == 0xA) || (codePoint == 0xD)
                    || ((codePoint >= 0x20) && (codePoint <= 0xD7FF))
                    || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD))
                    || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF))) {
                response.append(Character.toChars(codePoint));
            }
            i += Character.charCount(codePoint);
        }

        return response.toString().replace("\\\n", "").replace("\\\t", "");
    } catch (UnknownHostException e) {
        log.error("Cannot resolve host: " + socket.getInetAddress(), e);
        throw new IntegrationException(e.getMessage());
    } catch (IOException e) {
        log.error("Couldn't get I/O for the connection to: " + socket.getInetAddress(), e);
        throw new IntegrationException(e.getMessage());
    } finally {
        try {
            if (wr != null) {
                wr.close();
            }
            if (rd != null) {
                rd.close();
            }
        } catch (Throwable t) {
            log.error("close socket", t);
        }
    }
}

From source file:cit360.sandbox.BackEndMenu.java

public static final void smtpExample() {
    // declaration section:
    // smtpClient: our client socket
    // os: output stream
    // is: input stream
    Socket smtpSocket = null;
    DataOutputStream os = null;/* ww  w.  j av a  2 s.  c o m*/
    DataInputStream is = null;
    // Initialization section:
    // Try to open a socket on port 25
    // Try to open input and output streams
    try {
        smtpSocket = new Socket("localhost", 25);
        os = new DataOutputStream(smtpSocket.getOutputStream());
        is = new DataInputStream(smtpSocket.getInputStream());
    } catch (UnknownHostException e) {
        System.err.println("Did not recognize server: localhost");
    } catch (IOException e) {
        System.err.println("Was not able to open I/O connection to: localhost");
    }
    // If everything has been initialized then we want to write some data
    // to the socket we have opened a connection to on port 25
    if (smtpSocket != null && os != null && is != null) {
        try {

            os.writeBytes("HELO\n");
            os.writeBytes("MAIL From: david.banks0889@gmail.com\n");
            os.writeBytes("RCPT To: david.banks0889@gmail.com\n");
            os.writeBytes("DATA\n");
            os.writeBytes("From: david.banks0889@gmail.com\n");
            os.writeBytes("Subject: TEST\n");
            os.writeBytes("Hi there\n"); // message body
            os.writeBytes("\n.\n");
            os.writeBytes("QUIT");
            // keep on reading from/to the socket till we receive the "Ok" from SMTP,
            // once we received that then we want to break.
            String responseLine;
            while ((responseLine = is.readLine()) != null) {
                System.out.println("Server: " + responseLine);
                if (responseLine.contains("Ok")) {
                    break;
                }
            }
            // clean up:
            // close the output stream
            // close the input stream
            // close the socket
            os.close();
            is.close();
            smtpSocket.close();
        } catch (UnknownHostException e) {
            System.err.println("Trying to connect to unknown host: " + e);
        } catch (IOException e) {
            System.err.println("IOException:  " + e);
        }
    }
}

From source file:com.zhch.example.commons.http.v4_5.ProxyTunnelDemo.java

/**
 *  demo  //  ww w  .  ja  v  a  2 s. c om
 * 
 * @throws Exception
 */
public final static void zhchModifyDemo() throws Exception {

    ProxyClient proxyClient = new ProxyClient();
    HttpHost target = new HttpHost("pan.baidu.com", 80);
    //      HttpHost proxy = new HttpHost("120.24.0.162", 80);
    HttpHost proxy = new HttpHost("127.0.0.1", 80);
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("abc", "def");
    System.out.println("before tunnel.");
    Socket socket = proxyClient.tunnel(proxy, target, credentials);
    System.out.println("after tunnel.");

    try {
        Writer out = new OutputStreamWriter(socket.getOutputStream(), HTTP.DEF_CONTENT_CHARSET);
        out.write("GET / HTTP/1.1\r\n");
        out.write("Host: " + target.toHostString() + "\r\n");
        out.write("Agent: whatever\r\n");
        out.write("Connection: close\r\n");
        out.write("\r\n");
        out.flush();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(socket.getInputStream(), HTTP.DEF_CONTENT_CHARSET));
        String line = null;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }
    } finally {
        socket.close();
    }
}

From source file:com.yahoo.pulsar.zookeeper.LocalBookkeeperEnsemble.java

public static boolean waitForServerUp(String hp, long timeout) {
    long start = MathUtils.now();
    String split[] = hp.split(":");
    String host = split[0];/*from  w ww .  j  a  v a 2s  .  co  m*/
    int port = Integer.parseInt(split[1]);
    while (true) {
        try {
            Socket sock = new Socket(host, port);
            BufferedReader reader = null;
            try {
                OutputStream outstream = sock.getOutputStream();
                outstream.write("stat".getBytes());
                outstream.flush();

                reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
                String line = reader.readLine();
                if (line != null && line.startsWith("Zookeeper version:")) {
                    LOG.info("Server UP");
                    return true;
                }
            } finally {
                sock.close();
                if (reader != null) {
                    reader.close();
                }
            }
        } catch (IOException e) {
            // ignore as this is expected
            LOG.info("server " + hp + " not up " + e);
        }

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

From source file:EZShare.SubscribeCommandConnection.java

public static void establishPersistentConnection(Boolean secure, int port, String ip, int id,
        JSONObject unsubscribJsonObject, String commandname, String name, String owner, String description,
        String channel, String uri, List<String> tags, String ezserver, String secret, Boolean relay,
        String servers) throws URISyntaxException {
    //secure = false;
    try {//from   w w  w.  j  a v a  2 s . c  om
        System.out.print(port + ip);
        Socket socket = null;
        if (secure) {

            SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            socket = (SSLSocket) sslsocketfactory.createSocket(ip, port);
        } else {
            socket = new Socket(ip, port);
        }
        BufferedReader Reader = new BufferedReader(new InputStreamReader(System.in));
        DataOutputStream output = new DataOutputStream(socket.getOutputStream());
        DataInputStream input = new DataInputStream(socket.getInputStream());

        JSONObject command = new JSONObject();
        Resource resource = new Resource();
        command = resource.inputToJSON(commandname, id, name, owner, description, channel, uri, tags, ezserver,
                secret, relay, servers);

        output.writeUTF(command.toJSONString());
        Client.debug("SEND", command.toJSONString());
        //output.writeUTF(command.toJSONString());
        new Thread(new Runnable() {
            @Override
            public void run() {
                String string = null;
                try {
                    while (true/*(string = input.readUTF()) != null*/) {
                        String serverResponse = input.readUTF();
                        JSONParser parser = new JSONParser();
                        JSONObject response = (JSONObject) parser.parse(serverResponse);
                        Client.debug("RECEIVE", response.toJSONString());
                        //System.out.println(serverResponse);          
                        //                     if((string = Reader.readLine()) != null){
                        //                        if(onKeyPressed(output,string,unsubscribJsonObject)) break;
                        //                     }
                        if (flag == 1) {
                            break;
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                String string = null;
                try {
                    while ((string = Reader.readLine()) != null) {
                        flag = 1;
                        if (onKeyPressed(output, string, unsubscribJsonObject))
                            break;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.hadoop.hbase.zookeeper.MiniZooKeeperCluster.java

private static boolean waitForServerUp(int port, long timeout) throws IOException {
    long start = System.currentTimeMillis();
    while (true) {
        try {/*from w w  w  .j a v  a2  s . c o  m*/
            Socket sock = new Socket("localhost", port);
            BufferedReader reader = null;
            try {
                OutputStream outstream = sock.getOutputStream();
                outstream.write("stat".getBytes());
                outstream.flush();

                Reader isr = new InputStreamReader(sock.getInputStream());
                reader = new BufferedReader(isr);
                String line = reader.readLine();
                if (line != null && line.startsWith("Zookeeper version:")) {
                    return true;
                }
            } finally {
                sock.close();
                if (reader != null) {
                    reader.close();
                }
            }
        } catch (IOException e) {
            // ignore as this is expected
            LOG.info("server localhost:" + port + " not up " + e);
        }

        if (System.currentTimeMillis() > start + timeout) {
            break;
        }
        try {
            Thread.sleep(250);
        } catch (InterruptedException e) {
            throw (InterruptedIOException) new InterruptedIOException().initCause(e);
        }
    }
    return false;
}

From source file:expect4j.ExpectUtils.java

/**
 * Creates an HTTP client connection to a specified HTTP server and
 * returns the entire response.  This function simulates <code>curl
 * http://remotehost/url</code>.//from w ww  . j  a v  a 2s .c om
 *
 * @param remotehost the DNS or IP address of the HTTP server
 * @param url the path/file of the resource to look up on the HTTP
 *        server
 * @return the response from the HTTP server
 * @throws Exception upon a variety of error conditions
 */
public static String Http(String remotehost, String url) throws Exception {
    Socket s = null;
    s = new Socket(remotehost, 80);
    logger.debug("Connected to " + s.getInetAddress().toString());

    if (false) {
        // for serious connection-oriented debugging only
        PrintWriter out = new PrintWriter(s.getOutputStream(), false);
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

        System.out.println("Sending request");
        out.print("GET " + url + " HTTP/1.1\r\n");
        out.print("Host: " + remotehost + "\r\n");
        out.print("Connection: close\r\n");
        out.print("User-Agent: Expect4j\r\n");
        out.print("\r\n");
        out.flush();
        System.out.println("Request sent");

        System.out.println("Receiving response");
        String line;
        while ((line = in.readLine()) != null)
            System.out.println(line);
        System.out.println("Received response");
        if (line == null)
            System.exit(0);
    }

    Expect4j expect = new Expect4j(s);

    logger.debug("Sending HTTP request for " + url);
    expect.send("GET " + url + " HTTP/1.1\r\n");
    expect.send("Host: " + remotehost + "\r\n");
    expect.send("Connection: close\r\n");
    expect.send("User-Agent: Expect4j\r\n");
    expect.send("\r\n");

    logger.debug("Waiting for HTTP response");
    String remaining = null;
    expect.expect(new Match[] { new RegExpMatch("HTTP/1.[01] \\d{3} (.*)\n?\r", new Closure() {
        public void run(ExpectState state) {
            logger.trace("Detected HTTP Response Header");

            // save http code
            String match = state.getMatch();
            String parts[] = match.split(" ");

            state.addVar("httpCode", parts[1]);
            state.exp_continue();
        }
    }), new RegExpMatch("Content-Type: (.*\\/.*)\r\n", new Closure() {
        public void run(ExpectState state) {
            logger.trace("Detected Content-Type header");
            state.addVar("contentType", state.getMatch());
            state.exp_continue();
        }
    }), new EofMatch(new Closure() { // should cause entire page to be collected
        public void run(ExpectState state) {
            logger.trace("Found EOF, done receiving HTTP response");
        }
    }), // Will cause buffer to be filled up till end
            new TimeoutMatch(10000, new Closure() {
                public void run(ExpectState state) {
                    logger.trace("Timeout waiting for HTTP response");
                }
            }) });

    remaining = expect.getLastState().getBuffer(); // from EOF matching

    String httpCode = (String) expect.getLastState().getVar("httpCode");

    String contentType = (String) expect.getLastState().getVar("contentType");

    s.close();

    return remaining;
}

From source file:com.linkedin.d2.quorum.ZKPeer.java

/**
 * Send the 4letterword//  w  w w  .j a v  a2  s . c o  m
 *
 * @param host- destination host
 * @param port- destination port
 * @param cmd- the 4letterword (stat, srvr,etc. - see
 *          http://zookeeper.apache.org/doc/r3.3.3/zookeeperAdmin.html#sc_zkCommands)
 * @return
 * @throws IOException
 */
public static String sendCommand(String host, int port, String cmd) throws IOException {
    // NOTE: ignore CancelledKeyException in logs caused by
    // https://issues.apache.org/jira/browse/ZOOKEEPER-1237
    Socket sock = new Socket(host, port);
    BufferedReader reader = null;
    try {
        OutputStream outstream = sock.getOutputStream();
        outstream.write(cmd.getBytes());
        outstream.flush();
        sock.shutdownOutput();

        reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        return sb.toString();
    } finally {
        sock.close();
        if (reader != null) {
            reader.close();
        }
    }
}