繁体   English   中英

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

[英]InputStream.read() returning -1 after PrintWriter

下面的服务器和客户端代码尝试通过其名称发送文件:

  • 客户端使用PrintWriter发送文件名, PrintWriter在调用println后刷新。 之后,客户端使用while循环的常用方法发送文件内容,该循环读取文件,直到InputStream.read返回-1。
  • 服务器使用BufferedReader( readLine )读取文件名 之后,服务器使用相同的while循环读取文件内容。

问题是 :当服务器和客户端程序在同一台机器(我的Windows笔记本电脑)上本地执行时,一切都成功执行。 但是 ,当程序在同一网络上的不同机器上执行时,服务器端InputStream.read()返回-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();
    }

从评论: “你不能在同一个套接字上混合缓冲的流或读取器.BuffedReader将提前读取并消耗以下文件数据的一部分。”

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

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

(信用到@EJP)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM