Read all data from socket

asynchronous, java, sockets

Solution

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

Problem

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?

Original source