InputStream.read() 在 PrintWriter 之后返回 -1

InputStream.read() returning -1 after PrintWriter

下面的服务器和客户端代码尝试发送一个文件,其名称为:

问题是:当服务器和客户端程序在同一台机器(我的 Windows 笔记本电脑)上本地执行时,一切都会成功执行。 但是,当程序在同一网络的不同机器上执行时,服务器端InputStream.read()returns-1.

我不是在代码中寻找答案。(我已经用DataInputStream重写了)我想知道为什么是这样的

服务器:

try {
        ServerSocket server = new ServerSocket(3000);
        Socket client = server.accept();
        InputStream in = client.getInputStream();
        BufferedReader printIn = new BufferedReader(new InputStreamReader(in));
        String name = printIn.readLine();
        byte[] bytes = new byte[1024*16];
        File file = new File(name);
        FileOutputStream fOut = new FileOutputStream(file);
        int count;
        while ((count = in.read(bytes, 0, bytes.length)) != -1) {
            fOut.write(bytes, 0, count);
        }
        fOut.close();
        server.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

客户:

try {
        Socket client = new Socket("localhost",3000);
        OutputStream out = client.getOutputStream();
        PrintWriter printOut = new PrintWriter(out,true);
        printOut.println("old.jar");
        byte[] bytes = new byte[1024*16];
        File file = new File("old.jar");
        FileInputStream fIn = new FileInputStream(file);
        int count;
        while((count = fIn.read(bytes,0, bytes.length)) != -1) {
            out.write(bytes, 0, count);
        }
        fIn.close();
        client.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

来自评论:"You can't mix buffered streams or readers on the same socket. The BufferedReader will read ahead and consume part of the following file data."

因此,当在 BufferedReader.readLine() 之后调用 InputStream.read() 时,BufferedReader 会使用文件数据,所以 InputStream.read() returns -1.

关于代码在本地连接上成功执行的原因:本地连接的打包行为可能与远程连接不同

(归功于@EJP)