【问题标题】:Send File Multiple Time in Same Socket [duplicate]在同一个套接字中多次发送文件[重复]
【发布时间】:2017-10-18 22:36:23
【问题描述】:

我使用波纹管代码将文件文件主文件发送到客户端,但是当我使用多个时间时,此代码用于不同的文件程序会给出“SOCKET CLOSED”错误,因为我使用“out.close();”和“in”关闭了套接字。关();”我无法解决这些问题你有什么建议吗?我也尝试不关闭套接字,但它不起作用下一个文件这次不发送

private void SendFiletoClient(Socket Socket, String fileName) {
        try {
            File file = new File(MasterPath + "/" + fileName);// Get the size of the file
            long length = file.length();
            byte[] bytes = new byte[16 * 1024];
            InputStream in = new FileInputStream(file);
            OutputStream out = Socket.getOutputStream();

            int count;
            while ((count = in.read(bytes)) > 0) {
                out.write(bytes, 0, count);
            }

            out.close();
            in.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

/////

 private void addFileToClient(Socket Socket, String fileName) {

        File file = new File(MasterPath  + fileName);
        try {
            file.createNewFile();

            InputStream in = Socket.getInputStream();
            OutputStream out = new FileOutputStream(MasterPath  + fileName);

            byte[] bytes = new byte[16 * 1024];
            int count;
            while ((count = in.read(bytes)) > 0) {
                out.write(bytes, 0, count);
            }
            out.close();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

【问题讨论】:

  • 不要关闭套接字?
  • 试了很多次都没用
  • file.createNewFile(); 在这里毫无意义。您正在强制文件系统 (a) 删除任何现有文件,(b) 创建一个新文件,然后 (c) 在执行 new FileOutputStream() 时再次执行所有这些操作。这完全是浪费时间和空间。

标签: java sockets port


【解决方案1】:

因为你正在关闭套接字

  out.close();
  in.close();

要么不关闭套接字并保持连接处于活动状态,要么每次你想通过它发送东西时打开关闭。

在您的情况下,关闭输出(文件)并保持活动输入(套接字)。问题是,另一边会发生什么?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-01
    • 1970-01-01
    • 2016-09-12
    相关资源
    最近更新 更多