简体   繁体   中英

Read all data from socket

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?

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();
}

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();
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM