通过套接字传输文件

时间:2011-08-14 07:05:47

标签: java sockets file-transfer

抱歉,我已经改变了这个问题。

在这个code中,如果第一次发送文件(无论我发送的数字文件。)代码都可以正常工作。但是当我把FileSender放在循环中逐个发送文件时,在第一次传输之后,接收端接收的数据是任意的(如果在调试期间检查),它甚至都不会收到文件。这是我所做的改变而且它不起作用。 的 FileSender.java

import java.io.OutputStream;
import java.io.File;
import java.net.Socket;
public class FileSender {
public  void main(Socket socket,String[] args) {
try {

  OutputStream os     = socket.getOutputStream();
  int cnt_files = args.length;

  // How many files?
  ByteStream.toStream(os, cnt_files);

  for (int cur_file=0; cur_file<cnt_files; cur_file++) {
    ByteStream.toStream(os, new File(args[cur_file]).getName());
    ByteStream.toStream(os, new File(args[cur_file]));
  }
}
catch (Exception ex) {
  ex.printStackTrace();
}
}
}

String [] args包含要传输的文件的路径。

FileReceiver.java

import java.io.File;
import java.io.InputStream;
import java.net.Socket;

public class FileReceiver {

public void main(Socket socket,String arg) {
try {
    InputStream in = socket.getInputStream();

  int nof_files = ByteStream.toInt(in);
System.out.println("reach 1     "+ nof_files);
  for (int cur_file=0;cur_file < nof_files; cur_file++) {
    String file_name = ByteStream.toString(in);

    File file=new File(arg+file_name);
    System.out.println("Received path is :  "+file);
    ByteStream.toFile(in, file);
  }

}
catch (java.lang.Exception ex) {
  ex.printStackTrace(System.out);
}
}

}

arg包含文件存储的路径。

我希望每当我想传输文件时,我都会调用主要函数。基本上我想传输多个文件,这些文件也可以包含目录。为此,我编写了以下代码。

ServerFile.java

import java.io.*;
import java.net.*;
public class ClientFile implements Runnable{
Socket clientsocket;
public void run() {
    try
    {
        clientsocket = new Socket("219.64.189.14",6789);
    // Some code
    copy(outtoserver,infromserver, files);      // files contains the path of files to be transferred.
    // Some code
        clientsocket.close();
    }
    catch(Exception e2)
    {
            System.out.println("ClientFile   "+String.valueOf(e2) + "\n");
    }
}
public void copy(DataOutputStream outtoserver,BufferedReader infromserver,String[] files)
{
    try
    {
        FileSender fs = new FileSender();
        int totalfiles=0;
        int r=0;
        File oldfile;
        outtoserver.write(files.length);
        String chk;
        while(totalfiles<files.length)
        {

            oldfile = new File(files[totalfiles]);
            if(oldfile.isDirectory())
            {
                outtoserver.writeBytes("folder\n");
                File folder1[] = oldfile.listFiles();
                String[] folder = new String[folder1.length];
                int count=0;
                for(File name : folder1)
                {
                    folder[count] = name + "";
                    System.out.println(folder[count]);
                    count++;
                }
                outtoserver.writeBytes(oldfile.getName()+"\n");
                fs.main(clientsocket, folder);

            }
            else if(oldfile.isFile())
            {
                outtoserver.writeBytes("file\n");
        chk = infromserver.readLine();
                if(chk.equals("send"))
                {
                    outtoserver.writeBytes(oldfile.getName()+"\n");
                    String[] folder = new String[]{oldfile.getAbsolutePath()};
                    fs.main(clientsocket, folder);
                }
                totalfiles++;
                outtoserver.flush();

            }
        }
    }
    catch(Exception e)
    {
        System.out.println("ClientFile -->>  "+e.toString());
    }
}
}

ClientFile.java

import java.io.*;
import java.net.*;
import javax.swing.*;
class ServerFile implements Runnable {
Socket conn;
public ServerFile(Socket a)
{
    conn = a;
}
public void run() {
    File file1;
    String clientsen="";
    try
    {  // Some code
       copy(outtoclient,infromclient,file1.getAbsolutePath());      //file1 is the directory to which the file has to stored.    
   // some code
    }      
    catch(Exception e0)
    {
         System.out.println("ServerFile   "+String.valueOf(e0)+"\n"+e0.getCause());
    }
}//end main
public void copy(DataOutputStream outtoclient,BufferedReader infromclient,String basepath)
{
    try
    {
         FileReceiver fr = new FileReceiver();
         int totfiles = infromclient.read();
         int tot=0;
         File file;
         String path = null,chk;
         while(tot<totfiles)
         {
             chk = infromclient.readLine();
             if(chk.equals("file"))
             {
                outtoclient.writeBytes("send\n");
                path = infromclient.readLine();
                path = basepath+File.separator+path;
                file=new File(path);
                fr.main(conn, basepath+File.separator);
             }
             else if(chk.equals("folder"))
             {
                 String name = infromclient.readLine();
                 name = basepath+File.separator+name;
                 new File(name).mkdir();
                 fr.main(conn, name+File.separator);
             }
             tot++;
         }
    }
    catch(Exception e)
    {
        System.out.println("Server file:    "+e.toString());
    }
}

}//end class

如果我错了,请务必纠正我。

任何帮助表示感谢。

1 个答案:

答案 0 :(得分:1)

看起来您正在尝试将文件数设置为一(ByteStream.toStream(os, 1);),但随后您发送所有文件(从内部循环中的0到cnt_files-1),然后是args [ 0]试图在args []中使用下一个文件的事情。首先要解决这个问题,因为我认为你想要做的事情更多的是:

for(int i =0; i<n;i++){
    ByteStream.toStream(os, 1);//cnt_files);
    ByteStream.toStream(os, args[i]);
    ByteStream.toStream(os, new File(args[i]));
}

但仍然无法正常工作,因为另一端FileReceiver有这个:

int nof_files = ByteStream.toInt(in);

所以FileReceiver所做的第一件事就是看看有多少文件。它只会看到1,它的循环将结束,其他文件将无法读取。

如果“逐个”表示每个连接一个文件,那么你需要这样的东西:

public static void main(String[] args) {

    try {
        for(int i =0; i<args.length;i++){
            Socket socket = new Socket(host, port);
            OutputStream os = socket.getOutputStream();

            ByteStream.toStream(os, 1);//cnt_files);
            ByteStream.toStream(os, args[i]);
            ByteStream.toStream(os, new File(args[i]));

            os.close();
            socket.close();
        }
     }
     catch(Exception e) {
         e.printStackTrace();
     }
}