这是我正在使用的代码。
客户:
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();
}
服务器:
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();
}
文件 README.txt 中有大约 2400 个字节。当我运行它时,服务器会输出它。
1024
1869488225
然后它抛出一个 java.lang.OutOfMemoryError。
谁能告诉我为什么它读的是 1869488225 而不是 1024?
谢谢