tags:

views:

721

answers:

1

I have written a socket program using read() and write(). Whenever I want to send large data using write(). I am unable to recieve data at a time. Means my data is divided into two section so how can I send large amount of data. or read the data at 1 time. Also I am unable to know whether this is the problem of write() or read()

Thanks Bapi

+1  A: 

read() is only guaranteed to read 1 byte, anything more than that is a bonus.

A common way to handle this is to use DataOutputStream and DataInputStream to send the size of the "block" you want.

public static void write(DataOutput out, byte[] bytes) throws IOException {
    out.writeInt(bytes.length);
    out.write(bytes);
}

public static byte[] read(DataInput in) throws IOException {
    int len = in.readInt();
    byte[] bytes = new byte[len];
    in.readFully(bytes);
    return bytes;
}
Peter Lawrey
Actually, it's not even guaranteed to read that much... the socket might be in non-blocking mode; <smile>.
Software Monkey