TCP接收器循环

时间:2013-02-07 01:33:22

标签: java tcpclient file-transfer

我请求帮助 在客户端接收文件。变量输入记录文件名。 Inputstream“is”和FileOutputStream“bos”负责保存文件。第一个文件已交付,但另一个接收文件在变量名中出现java.lang.NullPointerException。如何处理此循环以创建文件,输入变量将包含文件的下一个新名称,流“is”将包含新数据? File poison.pill表示传输结束。

public class Receiver implements Runnable {


    private int port;

    public Receiver(int port) {

        this.port = port;

    }

    @Override
    public void run() {
        Socket socket = null;
        BufferedOutputStream bos = null;
        try {
            InetAddress adresa = InetAddress.getByName("localhost");

            System.out.println("klient sa pripaja na adresu: " + adresa);
            socket = new Socket(adresa, this.port);

            System.out.println("socket = " + socket);
            while (true) {
                BufferedReader input = new BufferedReader(
                        new InputStreamReader(socket.getInputStream()));
                String name = input.readLine();
            /// while (???????) {}



                if (name.equals("poison.pill")) {// null pointer exception

                    bos.close();
                    socket.close();
                    break;
                }

                int filesize = 1400;

                int bytesRead;
                byte[] bytearray = new byte[filesize];
                InputStream is = socket.getInputStream();
                FileOutputStream fos = new FileOutputStream(name);
                bos = new BufferedOutputStream(fos);

                while ((bytesRead = is.read(bytearray)) != -1) {
                    bos.write(bytearray, 0, bytesRead);
                    bos.flush();
                }

            }



        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

如果有误解我会解释。

1 个答案:

答案 0 :(得分:0)

也许我不理解你,但你想要什么?看看你的代码,你可以看到

  1. 从inputStream读取行 - > fileName input.readLine()
  2. 从输入流while ((bytesRead = is.read(bytearray)) != -1) {读取所有!!!! 数据-1表示流为空
  3. 在你的循环进入星形并尝试读取行(p1)之后,是的 stream为空(p2),您有NullPointer
  4. 解决方案,等到一些数据到达流...