簡體   English   中英

通過套接字傳輸文件

[英]File transfer through socket

對不起,但我已經改變了問題。

在這段代碼中,如果文件是第一次發送的(無論我發送的文件數量如何),代碼都可以正常工作。 但是當我把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 包含要傳輸的文件的路徑。

文件接收器.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 包含要存儲文件的路徑。

我希望每當我想傳輸文件時調用提到的主要功能。 基本上我想傳輸多個文件,這些文件也可以包含目錄。 為此,我編寫了以下代碼。

服務器文件.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

如果我錯了,一定要糾正我。

任何幫助表示贊賞。

看起來您正在嘗試將文件數設置為一個( 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();
     }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM