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: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 .  co m
        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  w w. jav a 2  s.  c o  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:io.selendroid.android.impl.DefaultAndroidEmulator.java

private static Map<String, Integer> mapDeviceNamesToSerial() {
    Map<String, Integer> mapping = new HashMap<String, Integer>();
    CommandLine command = new CommandLine(AndroidSdk.adb());
    command.addArgument("devices");
    Scanner scanner;//w  ww . j  av a2 s  . c o m
    try {
        scanner = new Scanner(ShellCommand.exec(command));
    } catch (ShellCommandException e) {
        return mapping;
    }
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        Pattern pattern = Pattern.compile("emulator-\\d\\d\\d\\d");
        Matcher matcher = pattern.matcher(line);
        if (matcher.find()) {
            String serial = matcher.group(0);

            Integer port = Integer.valueOf(serial.replaceAll("emulator-", ""));
            TelnetClient client = null;
            try {
                client = new TelnetClient(port);
                String avdName = client.sendCommand("avd name");
                mapping.put(avdName, port);
            } catch (AndroidDeviceException e) {
                // ignore
            } finally {
                if (client != null) {
                    client.close();
                }
            }
            Socket socket = null;
            PrintWriter out = null;
            BufferedReader in = null;
            try {
                socket = new Socket("127.0.0.1", port);
                out = new PrintWriter(socket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                if (in.readLine() == null) {
                    throw new AndroidDeviceException("error");
                }

                out.write("avd name\r\n");
                out.flush();
                in.readLine();// OK
                String avdName = in.readLine();
                mapping.put(avdName, port);
            } catch (Exception e) {
                // ignore
            } finally {
                try {
                    out.close();
                    in.close();
                    socket.close();
                } catch (Exception e) {
                    // do nothing
                }
            }
        }
    }
    scanner.close();

    return mapping;
}

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  ww w . j  ava2s  .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:MainClass.java

public void run() {
    try {/* w w  w .j  av a 2s  .c  om*/
        Socket client = serverSocket.accept();

        DataInputStream in = new DataInputStream(client.getInputStream());
        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        DataOutputStream out = new DataOutputStream(client.getOutputStream());

        while (true) {
            String message = in.readUTF();
            System.out.println(message);
            System.out.print("Enter response: ");
            String response = console.readLine();

            out.writeUTF(response);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:MainClass.java

public void run() {
    try {/*from  w ww .j a va  2  s.  c o m*/
        Socket socket = new Socket("127.0.0.1", 2000);

        DataInputStream in = new DataInputStream(socket.getInputStream());
        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        DataOutputStream out = new DataOutputStream(socket.getOutputStream());

        while (true) {
            System.out.print("Enter response: ");
            String response = console.readLine();
            out.writeUTF(response);

            String message = in.readUTF();
            System.out.println(message);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:Finger.java

public String finger(String host, String users) throws IOException, SocketException {
    String outstring = "";
    int c = 0;//from w  w  w .j a va  2  s  .  c  o m
    Socket sock = new Socket(host, 79);
    OutputStream os = sock.getOutputStream();
    InputStream is = sock.getInputStream();
    users = users + "\r\n";
    os.write(users.getBytes("iso8859_1"));
    try {
        while (c != -1) {
            c = is.read();
            if (c != -1)
                outstring += (char) c;
        }
    } catch (IOException e) {
    }
    return outstring;
}

From source file:com.nmote.smpp.TCPLink.java

public TCPLink(Socket socket, Logger log) throws IOException {
    super(socket.getInputStream(), socket.getOutputStream(), log);
    this.socket = socket;
}

From source file:DateServer.java

public void run() {
    while (true) {
        try {//from   w  ww  . j av  a2s. c o m
            Socket s = ss.accept();

            ObjectInputStream ois;
            ois = new ObjectInputStream(s.getInputStream());
            Locale l = (Locale) ois.readObject();

            PrintWriter pw;
            pw = new PrintWriter(s.getOutputStream());

            MessageFormat mf;
            mf = new MessageFormat("The date is {0, date, long}", l);

            Object[] args = { new Date() };

            pw.println(mf.format(args));

            pw.close();
        } catch (Exception e) {
            System.err.println(e);
        }
    }
}

From source file:org.alinous.net.mail.AbstractSmptCommand.java

protected String receive(Socket con) throws IOException {
    InputStream inStream = con.getInputStream();

    byte[] buff = new byte[256];
    int nRead = inStream.read(buff);

    String received = new String(buff, 0, nRead);

    return received;
}