【发布时间】:2015-08-04 02:56:36
【问题描述】:
我正在尝试通过套接字传输文件。我只使用了一个套接字进行通信(我猜不是根据 FTP 协议)。以下代码将成功传输第一个文件,但无法传输第二个文件,因为文件名没有改变,但服务器获取了读取的字节新的数据文件。我认为问题出在 readUTF 和 writeUTF 上。
这是我的服务器端代码。 记住这接受文件。不发送文件。
public int listenPort() throws IOException{
System.out.println("LISTENING");
try{
//this.dis = new DataInputStream(this.socketClient.getInputStream());
if( this.dis.available() != 0 ){
String filename = this.dis.readUTF();
this.fos = new FileOutputStream("/home/ankit07/" + filename);
int bytesRead = (int) IOUtils.copyLarge(this.dis,this.fos); //no of bytes copied
return bytesRead;
}else{
return 0;
}
}finally{
}
}
这是我的客户端。 记住这边发送文件。不接受
public void getFile(String filename) throws IOException{
try{
this.file = this.window.file;
DataOutputStream dos = new DataOutputStream(this.socketClient.getOutputStream());
dos.writeUTF(filename);
FileInputStream fis = new FileInputStream(this.file);
int readByte = (int) IOUtils.copyLarge(fis, dos);
System.out.println("FILE SENT : " + filename + " Bytes :" + readByte);
//this.socketClient.close();
}finally{
//if( this.os!=null) this.os.close();
if( this.window.file != null) this.window.file = null;
if( this.file != null) this.file = null;
//if( this.socketClient!=null) this.socketClient.close();
}
}
文件选择在其他类window中完成。
选择文件的方法在window类中。这有一个公共 File 属性来保存文件,然后我调用了 getFile(String filename) 来发送文件名并引用选定的文件,客户端有 File 属性来引用同一个文件。
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Object src = e.getSource();
if( src instanceof JButton ){ //Browse clicked
JFileChooser fc = new JFileChooser();
int returnVal = fc.showDialog(null, "SELECT FILE");
if( returnVal == JFileChooser.APPROVE_OPTION){
this.file = fc.getSelectedFile();
try {
this.sc.getFile(this.file.getName());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}else{
//unable to select file
}
}
}
除了我最初的问题外,我还无法传输像 mp3 和视频这样的大文件。如果您知道任何解决方案,那将会很有帮助。 谢谢你!!!!
【问题讨论】:
-
摆脱 available() 测试。
-
它不能解决问题。它仍然读取第一个文件但无法读取下一个文件..文件重新加载(发生刷新类型的事情)并且文件名仍然保持不变
标签: java sockets file-transfer