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: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;
                    }/*  w w w.ja v a  2  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:com.clough.android.adbv.manager.ADBManager.java

/**
 * Waiting for a device to connect and connect with it's one of eligible 
 * android application for AndroidDBViewer to run.
 * @return IOManager instance configured for a android application
 * @throws IOException/* w  w  w  .j  a  v  a2  s  . c  o  m*/
 * @throws ADBManagerException 
 */
public IOManager makeConnection() throws IOException, ADBManagerException {

    // Placing adb executable files for the desktop application use
    placeRelevantAdb();

    // Trying to connect with android application again and agian 
    // when ever an attempt is fail
    while (true) {
        try {

            // Creating a socket with PC_PORT and trying to connect with an server socket.
            // Connecting can fails due the ports not being forwarded or due to the
            // server socket not being started yet.
            // To be able to detect the server socket as running, a device must connected to the PC
            // and ADBVApplication configured android app must run on the device.
            final Socket deviceSocket = new Socket("localhost", PC_PORT);

            // Requesting to connect
            new PrintWriter(deviceSocket.getOutputStream(), true)
                    .println(new Data(Data.CONNECTION_REQUEST, "", "").toJSON().toString());
            Data recivedData = new Data(new JSONObject(
                    new BufferedReader(new InputStreamReader(deviceSocket.getInputStream())).readLine()));
            if (recivedData.getStatus() == Data.CONNECTION_ACCEPTED) {

                // Adding a shudown hook to disconnect the adb connection and close the socket connection
                Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

                    @Override
                    public void run() {
                        killServer();
                        try {
                            deviceSocket.shutdownInput();
                            deviceSocket.shutdownOutput();
                            deviceSocket.close();
                        } catch (IOException ex) {
                        }
                    }
                }));

                // Returning an IOManager created for this connection
                return new IOManager(deviceSocket);
            }
        } catch (IOException ex) {
            prepareADB();
        } catch (NullPointerException ex) {
            prepareADB();
        } catch (JSONException ex) {
            prepareADB();
        }
    }
}

From source file:com.shonshampain.streamrecorder.util.StreamProxy.java

private HttpRequest readRequest(Socket client) {
    HttpRequest request;/*from www . java  2s.  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) {
        Logger.e(TAG, "Error parsing request", e);
        return null;
    }

    if (firstLine == null) {
        Logger.d(DBG, TAG, "Proxy client closed connection without a request.");
        return null;
    }

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

From source file:org.kjkoster.zapcat.test.ZabbixAgentProtocolTest.java

/**
 * Test robustness.// w w  w  . j  av  a  2s  .  c  o  m
 * 
 * @throws Exception
 *             When the test failed.
 */
@Test
public void testMissingArgument() throws Exception {
    final Agent agent = new org.kjkoster.zapcat.zabbix.ZabbixAgent();
    // give the agent some time to open the port
    Thread.sleep(100);
    final Socket socket = new Socket(InetAddress.getLocalHost(),
            org.kjkoster.zapcat.zabbix.ZabbixAgent.DEFAULT_PORT);

    final Writer out = new OutputStreamWriter(socket.getOutputStream());
    out.write("jmx\n");
    out.flush();

    final InputStream in = socket.getInputStream();
    final byte[] buffer = new byte[1024];
    final int read = in.read(buffer);
    assertEquals(29, read);

    assertEquals('Z', buffer[0]);
    assertEquals('B', buffer[1]);
    assertEquals('X', buffer[2]);
    assertEquals('D', buffer[3]);

    assertEquals('N', buffer[17]);
    assertEquals('O', buffer[18]);
    assertEquals('T', buffer[19]);

    // we'll take the rest for granted...

    socket.close();
    agent.stop();
}

From source file:com.alibaba.dragoon.common.protocol.transport.socket.SocketSessionImpl.java

public SocketSessionImpl(Socket socket, AtomicLong receivedBytes, AtomicLong receivedMessages,
        AtomicLong sentBytes, AtomicLong sentMessages) {
    super();/*w ww .j a v a 2 s  .  co  m*/
    this.socket = socket;
    state = State.Established;

    this.receivedBytes = receivedBytes;
    this.receivedMessages = receivedMessages;
    this.sentBytes = sentBytes;
    this.sentMessages = sentMessages;

    try {
        dataInput = new DataInputStream(socket.getInputStream());
        writer = new DataOutputStream(socket.getOutputStream());
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException(e.getMessage(), e);
    } catch (IOException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}

From source file:org.kjkoster.zapcat.test.ZabbixAgentProtocolTest.java

/**
 * Test robustness./*from  ww  w . j a  v  a2 s. c  o m*/
 * 
 * @throws Exception
 *             When the test failed.
 */
@Test
public void testMissingClose() throws Exception {
    final Agent agent = new org.kjkoster.zapcat.zabbix.ZabbixAgent();
    // give the agent some time to open the port
    Thread.sleep(100);
    final Socket socket = new Socket(InetAddress.getLocalHost(),
            org.kjkoster.zapcat.zabbix.ZabbixAgent.DEFAULT_PORT);

    final Writer out = new OutputStreamWriter(socket.getOutputStream());
    out.write("jmx[foo\n");
    out.flush();

    final InputStream in = socket.getInputStream();
    final byte[] buffer = new byte[1024];
    final int read = in.read(buffer);
    assertEquals(29, read);

    assertEquals('Z', buffer[0]);
    assertEquals('B', buffer[1]);
    assertEquals('X', buffer[2]);
    assertEquals('D', buffer[3]);

    assertEquals('N', buffer[17]);
    assertEquals('O', buffer[18]);
    assertEquals('T', buffer[19]);

    // we'll take the rest for granted...

    socket.close();
    agent.stop();
}

From source file:epn.edu.ec.bibliotecadigital.cliente.Client.java

@Override
public void run() {
    try {/*from  w  w w  . ja  v a  2s. c  o m*/
        clientSocketBalancer = new Socket(InetAddress.getByName(serverIP), portBalancer);
        DataInputStream dataInBalancer = new DataInputStream(clientSocketBalancer.getInputStream());
        DataOutputStream dataOut = new DataOutputStream(clientSocketBalancer.getOutputStream());
        dataOut.writeUTF((String) params[0]);//nombre de usuario
        String ipServer = dataInBalancer.readUTF();
        int portServer = dataInBalancer.readInt();
        clientSocketBalancer.close();
        Socket clientSocket = new Socket(ipServer, portServer);
        dataOut = new DataOutputStream(clientSocket.getOutputStream());
        dataOut.writeUTF(accion);
        dataOut.writeUTF((String) params[0]);//nombre de usuario
        InputStream in;
        DataInputStream dataIn;
        switch (accion) {
        case "bajar":

            dataOut = new DataOutputStream(clientSocket.getOutputStream());
            dataOut.writeUTF((String) params[1]);
            dataIn = new DataInputStream(clientSocket.getInputStream());
            boolean encontrado = dataIn.readBoolean();
            if (!encontrado) {
                System.out.println("Libro con el cdigo: " + params[1] + " no encontrado");
                break;
            }
            String fileName = dataIn.readUTF();
            System.out.println(
                    "Descargando libro " + fileName + " con cdigo " + params[1] + " en la carpeta Donwloads");
            String home = System.getProperty("user.home");

            in = clientSocket.getInputStream();
            try {
                FileOutputStream out = new FileOutputStream(new File(home + "\\Downloads\\" + fileName));
                byte[] bytes = new byte[64 * 1024];

                int count;
                while ((count = in.read(bytes)) > 0) {
                    out.write(bytes, 0, count);
                }
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                IOUtils.closeQuietly(in);
            }
            break;
        case "subir":
            dataOut = new DataOutputStream(clientSocket.getOutputStream());
            dataOut.writeUTF(((File) params[1]).getName());
            OutputStream out = clientSocket.getOutputStream();
            try {
                byte[] bytes = new byte[64 * 1024];
                in = new FileInputStream((File) params[1]);

                int count;
                while ((count = in.read(bytes)) > 0) {
                    out.write(bytes, 0, count);
                }
                in.close();
            } finally {
                IOUtils.closeQuietly(out);
            }
            break;
        case "obtenerLista":
            ObjectInputStream inFromClient = new ObjectInputStream(clientSocket.getInputStream());
            System.out.println("Libros disponibles: \n");
            List<Libro> libros = (List<Libro>) inFromClient.readObject();
            System.out.println("\tCdigo\tNommbre\n");
            for (Libro lbr : libros) {
                System.out.println("\t" + lbr.getCodigolibro() + "\t" + lbr.getNombre());
            }
            inFromClient.close();
            break;
        case "verificar":

            break;
        }
        dataOut.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.kjkoster.zapcat.test.ZabbixAgentProtocolTest.java

/**
 * Test the we can ping the agent.//  www  . ja v  a 2 s  . c om
 * 
 * @throws Exception
 *             When the test failed.
 */
@Test
public void testPing() throws Exception {
    final Agent agent = new org.kjkoster.zapcat.zabbix.ZabbixAgent();
    // give the agent some time to open the port
    Thread.sleep(100);
    final Socket socket = new Socket(InetAddress.getLocalHost(),
            org.kjkoster.zapcat.zabbix.ZabbixAgent.DEFAULT_PORT);

    final Writer out = new OutputStreamWriter(socket.getOutputStream());
    out.write("agent.ping\n");
    out.flush();

    final InputStream in = socket.getInputStream();
    final byte[] buffer = new byte[1024];
    final int read = in.read(buffer);
    assertEquals(14, read);

    assertEquals('Z', buffer[0]);
    assertEquals('B', buffer[1]);
    assertEquals('X', buffer[2]);
    assertEquals('D', buffer[3]);

    assertEquals('1', buffer[13]);

    // we'll take the rest for granted...

    socket.close();
    agent.stop();
}

From source file:org.kjkoster.zapcat.test.ZabbixAgentProtocolTest.java

/**
 * Test robustness.//  w  ww.j  a  v  a 2 s.  c om
 * 
 * @throws Exception
 *             When the test failed.
 */
@Test
public void testMissingOpen() throws Exception {
    final Agent agent = new org.kjkoster.zapcat.zabbix.ZabbixAgent();
    // give the agent some time to open the port
    Thread.sleep(100);
    final Socket socket = new Socket(InetAddress.getLocalHost(),
            org.kjkoster.zapcat.zabbix.ZabbixAgent.DEFAULT_PORT);

    final Writer out = new OutputStreamWriter(socket.getOutputStream());
    out.write("jmx(foo]\n");
    out.flush();

    final InputStream in = socket.getInputStream();
    final byte[] buffer = new byte[1024];
    final int read = in.read(buffer);
    assertEquals(29, read);

    assertEquals('Z', buffer[0]);
    assertEquals('B', buffer[1]);
    assertEquals('X', buffer[2]);
    assertEquals('D', buffer[3]);

    assertEquals('N', buffer[17]);
    assertEquals('O', buffer[18]);
    assertEquals('T', buffer[19]);

    // we'll take the rest for granted...

    socket.close();
    agent.stop();
}

From source file:br.gov.frameworkdemoiselle.monitoring.internal.implementation.zabbix.ZabbixSender.java

/**
 * @param key/*from w w  w  . java 2s  .  c  om*/
 * @param value
 * @throws IOException
 */
private void send(final String key, final String value) throws IOException {

    final long start = System.currentTimeMillis();

    final StringBuilder message = new StringBuilder(head);
    message.append(encodeBase64(key));
    message.append(middle);
    message.append(encodeBase64(value == null ? "" : value));
    message.append(tail);

    logger.debug(bundle.getString("zabbix-sender-sending-message", this.zabbixHost, key, value));
    logger.trace(bundle.getString("zabbix-sender-detailed-message", message));

    Socket socket = null;
    OutputStreamWriter out = null;
    InputStream in = null;

    try {
        socket = new Socket(zabbixServer, zabbixPort);
        socket.setSoTimeout(TIMEOUT);

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

        in = socket.getInputStream();
        final int read = in.read(response);

        final String resp = new String(response);
        logger.debug(bundle.getString("zabbix-sender-received-response", resp));
        if (read != 2 || response[0] != 'O' || response[1] != 'K') {
            logger.warn(bundle.getString("zabbix-sender-unexpected-response", key, resp));
        }

    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
        if (socket != null) {
            socket.close();
        }
    }

    final long elapsed = System.currentTimeMillis() - start;
    logger.trace(bundle.getString("zabbix-sender-message-sent", elapsed));
}