Read all data from socket

15,123

Solution 1

If you know the size of incoming data you could use a method like :

public int read(char cbuf[], int off, int len) throws IOException;

where cbuf is Destination buffer.

Otherwise, you'll have to read lines or read bytes. Streams aren't aware of the size of incoming data. The can only sequentially read until end is reached (read method returns -1)

refer here streams doc

sth like that:

public static String readAll(Socket socket) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null)
        sb.append(line).append("\n");
    return sb.toString();
}

Solution 2

You could use something like this:

   public static String readToEnd(InputStream in) throws IOException {
      byte[] b = new byte[1024];
      int n;
      StringBuilder sb = new StringBuilder();
      while ((n = in.read(b)) >= 0) {
         sb.append(b);
      }
      return sb.toString();
   }
Share:
15,123

Related videos on Youtube

Andrew Thompson
Author by

Andrew Thompson

Java desktop app. enthusiast (for the x-platform, rich client experience). No strong opinions on technologies, platforms etc. beyond that. Author of the SSCCE and wrote the initial draft of the MCVE at SO. Also seen at DrewTubeish. Some of the tools formerly available at my pscode.org domain can be downloaded from my Google Share Drive. At StackExchange: Completed the Java Web Start, JNLP, Applet & Java Sound tag information pages. Top user in same tags. Asked the How to create screenshots? FAQ & wrote the Why CS teachers should stop teaching Java applets blog post. One of the most prolific editors of questions & answers. Most active on StackOverflow but also seen at other places around StackExchange such as Space Exploration, Sci-Fi & Fantasy & Movies & TV.

Updated on September 14, 2022

Comments

  • Andrew Thompson
    Andrew Thompson over 1 year

    I want read all data ,synchronously , receive from client or server without readline() method in java(like readall() in c++).
    I don't want use something like code below:

    BufferedReader reader = new BufferedReader(new inputStreamReader(socket.getInputStream()));
    String line = null;
    while ((line = reader.readLine()) != null)
         document.append(line + "\n");
    

    What method should i use?

  • Tala
    Tala almost 11 years
    I've given you example since there is one more important thing to note: you should be using StringBuilder instead of concatting strings.
  • Vishy
    Vishy almost 11 years
    +1 Note: this will read all the characters, If there are incomplete multi-byte characters, it will be kept in the buffer and will appear later.
  • kroiz
    kroiz over 8 years
    @Tala, Use of StringBuilder for regular concatenations is obsolete at obsolete java optimization tips as well as at java urban myths.