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:fm.last.moji.tracker.impl.AbstractTrackerFactory.java

public Tracker newTracker(InetSocketAddress newAddress) throws TrackerException {
    log.debug("new {}()", TrackerImpl.class.getSimpleName());
    Tracker tracker = null;//from ww  w  . jav  a2 s. c  o m
    BufferedReader reader = null;
    Writer writer = null;
    Socket socket = null;
    try {
        socket = new Socket(netConfig.getProxy());
        socket.setSoTimeout(netConfig.getTrackerReadTimeout());
        log.debug("Connecting to: {}:", newAddress, socket.getPort());
        socket.connect(newAddress, netConfig.getTrackerConnectTimeout());
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        RequestHandler requestHandler = new RequestHandler(writer, reader);
        tracker = new TrackerImpl(socket, requestHandler);
    } catch (IOException e) {
        IOUtils.closeQuietly(reader);
        IOUtils.closeQuietly(writer);
        IOUtils.closeQuietly(socket);
        throw new TrackerException(e);
    }
    return tracker;
}

From source file:io.fabric8.kubernetes.api.KubernetesHelper.java

public static boolean isServiceSsl(String host, int port, boolean trustAllCerts) {
    try {//ww  w . ja v a 2  s.  co m
        SSLSocketFactory sslsocketfactory = null;
        if (trustAllCerts) {
            sslsocketfactory = KubernetesFactory.TrustEverythingSSLTrustManager.getTrustingSSLSocketFactory();
        } else {
            sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
        }

        Socket socket = sslsocketfactory.createSocket();

        // Connect, with an explicit timeout value
        socket.connect(new InetSocketAddress(host, port), 1 * 1000);
        try {

            InputStream in = socket.getInputStream();
            OutputStream out = socket.getOutputStream();

            // Write a test byte to get a reaction :)
            out.write(1);

            while (in.available() > 0) {
                System.out.print(in.read());
            }

            return true;
        } finally {
            socket.close();
        }
    } catch (SSLHandshakeException e) {
        LOG.error(
                "SSL handshake failed - this probably means that you need to trust the kubernetes root SSL certificate or set the environment variable "
                        + KubernetesFactory.KUBERNETES_TRUST_ALL_CERIFICATES,
                e);
    } catch (SSLProtocolException e) {
        LOG.error("SSL protocol error", e);
    } catch (SSLKeyException e) {
        LOG.error("Bad SSL key", e);
    } catch (SSLPeerUnverifiedException e) {
        LOG.error("Could not verify server", e);
    } catch (SSLException e) {
        LOG.debug("Address does not appear to be SSL-enabled - falling back to http", e);
    } catch (IOException e) {
        LOG.debug("Failed to validate service", e);
    }
    return false;
}

From source file:net.lightbody.bmp.proxy.jetty.http.SocketListener.java

/** Create an HttpConnection instance. This method can be used to
 * override the connection instance./*ww w.  jav  a 2  s  . c  o m*/
 * @param socket The underlying socket.
 */
protected HttpConnection createConnection(Socket socket) throws IOException {
    HttpConnection c = new HttpConnection(this, socket.getInetAddress(), socket.getInputStream(),
            socket.getOutputStream(), socket);
    return c;
}

From source file:audio.StreamProxy.java

private HttpRequest readRequest(Socket client) {
    HttpRequest request = null;/*from  w w w  .j a  v a 2  s.c  o m*/
    InputStream is;
    String firstLine;
    try {
        is = client.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8192);
        firstLine = reader.readLine();
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error parsing request", e);
        return request;
    }

    if (firstLine == null) {
        Log.i(LOG_TAG, "Proxy client closed connection without a request.");
        return request;
    }

    StringTokenizer st = new StringTokenizer(firstLine);
    String method = st.nextToken();
    String uri = st.nextToken();
    Log.d(LOG_TAG, uri);
    String realUri = uri.substring(1);
    Log.d(LOG_TAG, realUri);
    request = new BasicHttpRequest(method, realUri);
    return request;
}

From source file:com.sshtools.daemon.SshServer.java

/**
 *
 *
 * @param command//from  ww  w  .  ja  v a2 s. c  o m
 * @param client
 *
 * @throws IOException
 */
protected void processCommand(int command, Socket client) throws IOException {
    if (command == 0x3a) {
        int len = client.getInputStream().read();
        byte[] msg = new byte[len];
        client.getInputStream().read(msg);
        stopServer(new String(msg));
    }
}

From source file:com.clustercontrol.hinemosagent.util.AgentConnectUtil.java

/**
 * common.agent.discovery.pingport ????????IP??
 *  ?TCP???????true?//from  w  ww.j  a  v a 2  s  . com
 *  ?????????false?
 *
 * @param facilityId
 * @return
 * @throws UnknownHostException
 * @throws IOException
 */
public static boolean sendManagerDiscoveryInfo(String facilityId) throws UnknownHostException, IOException {
    String managerIpAddr = "";
    boolean successFlag = true;
    String agentIpAddr = "";
    int pingPort;

    // ???????????????????
    pingPort = HinemosPropertyUtil.getHinemosPropertyNum("common.agent.discovery.pingport", Long.valueOf(24005))
            .intValue();
    if (pingPort < 1 || pingPort > 65535) {
        return false;
    }
    // ???????IP?
    try {
        // DNS????(agent.connection.dnsname??) Hinemos ver 4.0.2?
        managerIpAddr = HinemosPropertyUtil.getHinemosPropertyStr("agent.connection.dnsname", "");

        // IP??(agent.connection.dnsname?)
        if (managerIpAddr == null || "".equals(managerIpAddr)) {
            managerIpAddr = HinemosPropertyUtil.getHinemosPropertyStr("agent.connection.ipaddres",
                    InetAddress.getLocalHost().getHostAddress());
        }
    } catch (UnknownHostException e) {
        throw e;
    }

    // FIXME ??????????????????????????????
    Socket socket = null;
    InputStream is = null;
    try {
        String sendDataStr = "managerIp=" + managerIpAddr + ",agentFacilityId=" + facilityId;
        byte[] data = sendDataStr.getBytes();
        byte[] msg = new byte[data.length];
        agentIpAddr = NodeProperty.getProperty(facilityId).getAvailableIpAddress();

        m_log.info("trying to establish connection to hinemos agent server at " + agentIpAddr + ":" + pingPort);

        socket = new Socket(agentIpAddr, pingPort);

        m_log.info("established the connection to the hinemos agent server at " + agentIpAddr);

        is = socket.getInputStream();
        OutputStream out = socket.getOutputStream();
        out.write(data);

        m_log.info("sent the message " + new String(data));

        // ???
        int totalBytesRcvd = 0;
        int bytesRcvd;

        while (totalBytesRcvd < data.length) {
            if ((bytesRcvd = is.read(msg, totalBytesRcvd, data.length - totalBytesRcvd)) == -1) {
                continue;
            }
            totalBytesRcvd += bytesRcvd;
        }
        m_log.info("received the message: " + new String(msg));
    } catch (Exception e) {
        successFlag = false;
        m_log.warn("facilityId: " + facilityId + ", " + e.getMessage());
    } finally {
        try {
            if (is != null) {
                is.close();
            }
            if (socket != null) {
                socket.close();
            }
        } catch (IOException e) {
            throw e;
        }
    }

    return successFlag;
}

From source file:com.code.android.vibevault.StreamProxy.java

private HttpRequest readRequest(Socket client) {
    HttpRequest request = null;/*from   w  w w.j  a v  a2  s  . c  o m*/
    InputStream is;
    String firstLine;
    try {
        is = client.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        firstLine = reader.readLine();
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error parsing request", e);
        return request;
    }

    if (firstLine == null) {
        Log.i(LOG_TAG, "Proxy client closed connection without a request.");
        return request;
    }

    StringTokenizer st = new StringTokenizer(firstLine);
    String method = st.nextToken();
    String uri = st.nextToken();

    String realUri = uri.substring(1);

    request = new BasicHttpRequest(method, realUri);
    return request;
}

From source file:org.prx.prp.StreamProxy.java

private HttpRequest readRequest(Socket client) {
    HttpRequest request = null;//from  w  w w  .j a  v  a 2s . co  m
    InputStream is;
    String firstLine;
    try {
        is = client.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        firstLine = reader.readLine();
    } catch (IOException e) {
        Log.e(getClass().getName(), "Error parsing request", e);
        return request;
    }

    StringTokenizer st = new StringTokenizer(firstLine);
    String method = st.nextToken();
    String uri = st.nextToken();
    Log.d(getClass().getName(), uri);
    String realUri = uri.substring(1);
    Log.d(getClass().getName(), realUri);
    request = new BasicHttpRequest(method, realUri);
    return request;
}

From source file:com.tomcat.monitor.zabbix.ZabbixSender.java

public void send(final String zabbixServer, final int zabbixPort, int zabbixTimeout, final String host,
        final String key, final String value) throws IOException {

    final byte[] response = new byte[1024];

    final long start = System.currentTimeMillis();

    final int TIMEOUT = zabbixTimeout * 1000;

    final StringBuilder message = new StringBuilder("<req><host>");
    message.append(new String(Base64.encodeBase64(host.getBytes())));
    message.append("</host><key>");
    message.append(new String(Base64.encodeBase64(key.getBytes())));
    message.append("</key><data>");
    message.append(new String(Base64.encodeBase64(value.getBytes())));
    message.append("</data></req>");

    if (log.isDebugEnabled()) {
        log.debug("sending " + message);
    }//from   w  w w.  j  a v  a 2  s  . c  om

    Socket zabbix = null;
    OutputStreamWriter out = null;
    InputStream in = null;
    try {
        zabbix = new Socket(zabbixServer, zabbixPort);
        zabbix.setSoTimeout(TIMEOUT);

        out = new OutputStreamWriter(zabbix.getOutputStream());
        out.write(message.toString());
        out.flush();

        in = zabbix.getInputStream();
        final int read = in.read(response);
        if (log.isDebugEnabled()) {
            log.debug("received " + new String(response));
        }
        if (read != 2 || response[0] != 'O' || response[1] != 'K') {
            log.warn("received unexpected response '" + new String(response) + "' for key '" + key + "'");
        }
    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
        if (zabbix != null) {
            zabbix.close();
        }
    }
    log.info("send() " + (System.currentTimeMillis() - start) + " ms");
}

From source file:com.chigix.bio.proxy.buffer.FixedBufferTest.java

License:asdf

@Test
public void testHTTPS() {
    System.out.println("BANKAI");
    Socket tmp_socket = null;/*from www  .j  ava2  s. co  m*/
    try {
        tmp_socket = new Socket("jp.jfwq.net", 6002);
    } catch (IOException ex) {
        Logger.getLogger(FixedBufferTest.class.getName()).log(Level.SEVERE, null, ex);
    }
    final Socket socket = tmp_socket;
    new Thread() {

        @Override
        public void run() {
            while (true) {
                try {
                    int read;
                    System.out.print(read = socket.getInputStream().read());
                    System.out.print((char) read);
                    System.out.print(",");
                } catch (IOException ex) {
                    Logger.getLogger(FixedBufferTest.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

    }.start();
    try {
        socket.getOutputStream()
                .write("CONNECT www.dnspod.cn:443 HTTP/1.1\nHost: www.dnspod.cn:443\n\n".getBytes());
    } catch (IOException ex) {
        Logger.getLogger(FixedBufferTest.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        Thread.sleep(50000);
    } catch (InterruptedException ex) {
        Logger.getLogger(FixedBufferTest.class.getName()).log(Level.SEVERE, null, ex);
    }
}