【问题标题】:Transfering file over a socket in ftp protocol在 ftp 协议中通过套接字传输文件
【发布时间】:2013-01-31 23:13:36
【问题描述】:

我在通过套接字发送文件(不一定是 txt 文件)时遇到问题。我有 2 个类:服务器、客户端。当我从套接字输出流中读取并想将字节写入文件时,它看起来工作,但当我打开文件时它什么都没有。(损坏显示大小= 0 kb)。我还希望它通过套接字传输所有类型的文件。我不想使用appache commons net。 这是我的代码 服务器类

FileOutputStream toFile1 = new FileOutputStream(f);             
BufferedOutputStream toFile= new BufferedOutputStream(toFile1);
BufferedInputStream bis=new BufferedInputStream(incoming.getInputStream());
byte[]buffer=new byte[2048];
int bytesRead=0;



while((bytesRead = bis.read(buffer)) >= 0)
{   
    toFile.write(buffer, 0, bytesRead);

}

toFile.close();
toFile1.close();
bis.close();
out.println("226 Connection Closed");
out.flush();
                  }                  

客户端类

 BufferedOutputStream output = new BufferedOutputStream(socket.getOutputStream());
 byte[] buffer = new byte[60*2024];
 int bytesRead = 0;
 while ((bytesRead = input.read(buffer,0,60*1024)) != -1) {
        output.write(buffer, 0, bytesRead);
 }

【问题讨论】:

    标签: java sockets ftp serversocket


    【解决方案1】:

    该代码可能发生的唯一方法是,如果您正在发送一个零长度文件,或者可能从已经定位在 EOF 的文件输入流中读取,或者您之后正在查看错误的文件。

    【讨论】:

    • 谢谢大家。我必须在客户端结束时刷新并关闭输出。我还有一个问题:如果在工作过程中,客户端断开连接,服务器应该怎么做?
    • @Proud 关闭数据连接,中止操作,通过命令连接报错。根据您的要求,可能会删除部分上传。如果您在写入命令通道时遇到异常,也请关闭它。
    猜你喜欢
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多