如何在第一次文件传输后保持套接字打开,以便将来可以传输更多文件

时间:2014-01-17 17:14:53

标签: sockets

下面我将一个带有名字的文件发送给客户。稍后我想通过同一个套接字将更多文件发送到同一个客户端。

这是我的服务器代码:

 BufferedOutputStream out = null;
    try {
        JFileChooser fr = new JFileChooser();
        FileSystemView fw = fr.getFileSystemView();
        String path = fw.getDefaultDirectory() + "\\1 (2).jpg";
        File file = new File(path);
        out = new BufferedOutputStream(client.getOutputStream());
        try (DataOutputStream d = new DataOutputStream(out)) {
            d.writeUTF(path);
            Files.copy(file.toPath(), d);
        }
    } catch (IOException ex) {
        Logger.getLogger(App_window.class.getName()).log(Level.SEVERE, null, ex);
    }

这是客户端的代码:

  BufferedInputStream in = null;
    try {
        in = new BufferedInputStream(server.getInputStream());
        try (DataInputStream d = new DataInputStream(in)) {
            String fileName = d.readUTF();
            //   System.out.println(fileName);


            File f4 = new File(fileName);
            if (f4.exists()) {
                f4.delete();
            }
            Files.copy(d, Paths.get(fileName));
        }
    } catch (IOException ex) {
        Logger.getLogger(App_window.class.getName()).log(Level.SEVERE, null, ex);
    }

1 个答案:

答案 0 :(得分:0)

根据The try-with-resources Statement,当离开try (DataInputStream d = new DataInputStream(in)) ...时,DataInputStream d将被关闭。

DataInputStream实施Closableclose()定义为Closes this stream and releases any system resources associated with it.

因此,来自InputStream的{​​{1}}也会被关闭。见this post

因此,要继续发送数据,请不要关闭任何流。只需使用server.getInputStream()而不是try{}catch{}

编辑:默认情况下,Socket将保持活动状态,从客户端或服务器调用try(...){}catch{}