Reputation: 1267
Here is the code I am using.
Client:
public static void main(String[] args) throws IOException {
Socket socket = new Socket("0.0.0.0", 5555);
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
FileInputStream in = new FileInputStream("C:/Documents and Settings/Owner/Desktop/Client/README.txt");
byte[] b = new byte[1024];
int i = 0;
i = in.read(b);
out.writeInt(i);
out.write(b, 0, i);
out.flush();
i = in.read(b);
out.writeInt(i);
out.write(b, 0, i);
out.flush();
out.close();
in.close();
socket.close();
}
Server:
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(5555);
Socket s = ss.accept();
ObjectInputStream in = new ObjectInputStream(s.getInputStream());
FileOutputStream fos = new FileOutputStream("C:/README.txt");
int i = 0;
i = in.readInt();
System.out.println(i);
byte[] bytes = new byte[i];
in.read(bytes);
i = in.readInt();
System.out.println(i);
byte[] bytes2 = new byte[i];
in.read(bytes2);
fos.write(bytes);
fos.close();
s.close();
ss.close();
}
The file README.txt has ~2400 bytes in it. When I run this, the server outputs this.
1024
1869488225
It then throws a java.lang.OutOfMemoryError.
Can anybody tell me why it is reading 1869488225 instead of 1024?
Thanks
Upvotes: 1
Views: 167
Reputation: 310860
in.read(bytes);
in.read(bytes2);
Here you are ignoring the return value of read and assuming that it fills the buffer. You should change read()
to readFully()
here, but in general you should never ignore a read()
result. It can be -1 indicating EOS, or it can be any count from 1 up to the buffer size. If you inadvertently specify a zero length buffer it can even be zero.
Upvotes: 1