Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/apache-spark/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在java中通过套接字编程传输zip文件?_Java_Sockets_Serversocket - Fatal编程技术网

如何在java中通过套接字编程传输zip文件?

如何在java中通过套接字编程传输zip文件?,java,sockets,serversocket,Java,Sockets,Serversocket,我不熟悉套接字编程。我做了一个简单的程序来传输zip文件,但这只是创建一个空的zip,不传输任何文件。你能帮我吗 Client.java package fileTransfer; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; public c

我不熟悉套接字编程。我做了一个简单的程序来传输zip文件,但这只是创建一个空的zip,不传输任何文件。你能帮我吗

Client.java

package fileTransfer;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

public class SimpleClient {

  public final static int SOCKET_PORT = 13267;      
  public final static String SERVER = "00.200.00.00";  
  public final static String
       FILE_TO_RECEIVED = "D:/Projects/Transferred.zip";  

  public final static int FILE_SIZE = 6022386; 


  public static void main (String [] args ) throws IOException {
    int bytesRead;
    int current = 0;
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    Socket sock = null;
    try {
      sock = new Socket(SERVER, SOCKET_PORT);
      System.out.println("Connecting...");

      // receive file
      byte [] mybytearray  = new byte [FILE_SIZE];
      InputStream is = sock.getInputStream();
      fos = new FileOutputStream(FILE_TO_RECEIVED);
      bos = new BufferedOutputStream(fos);
      bytesRead = is.read(mybytearray,0,mybytearray.length);
      current = bytesRead;

      do {
         bytesRead =
            is.read(mybytearray, current, (mybytearray.length-current));
         if(bytesRead >= 0) current += bytesRead;
      } while(current < FILE_SIZE);

      bos.write(mybytearray, 0 , current);
      bos.flush();
      System.out.println("File " + FILE_TO_RECEIVED    + " downloaded (" + current + " bytes read)");
    }
    finally {
      if (fos != null) fos.close();
      if (bos != null) bos.close();
      if (sock != null) sock.close();
    }
  }

}

请帮我解决这个问题

尝试在客户端以这种方式读取文件:

    Socket s = servsock.accept();

    InputStream in = s.getInputStream();
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("YOUR_FILE"));

    int c=0;
    byte[] buff=new byte[2048];

    while((c=in.read(buff))>0){ // read something from inputstream into buffer
        // if something was read 
        bos.write(buff, 0, c);
    }

    in.close();
    bos.close();

在服务器端执行同样的操作。您的
InputStream
将是一个文件,而输出将是一个套接字。它是复制流的强大方式。

我终于能够通过套接字传输zip文件。请在下面查找代码。 如果有人觉得可以做得更好。请让我知道:

Client.java

public class Client {
    public final static int SOCKET_PORT = 13267;      
    public final static String SERVER = "00.200.00.00";  
    public final static String
    FILE_TO_RECEIVED = "D:/Projects/Transferred.zip";
    public final static int FILE_SIZE = 5830740;
    public static void main(String args[]) {
        int bytesRead;
        int current = 0;
        PrintWriter pwr=null;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        BufferedReader br = null;
        Socket sock = null;
        String filesize= null, s=null;

        try {
            sock = connectToServer(SERVER, SOCKET_PORT);
            System.out.println("Connecting...");
            br= new BufferedReader(new InputStreamReader(sock.getInputStream()));
            pwr = new PrintWriter(sock.getOutputStream());
            String input=null, output = "SENDZIP";
            while((input = br.readLine()) != null){
                System.out.println("INPUT is "+input);
                if (input.contains("SENTZIP")){
                    byte [] mybytearray  = new byte [Integer.parseInt(s)];
                    InputStream is = sock.getInputStream();
                    fos = new FileOutputStream(FILE_TO_RECEIVED);
                    bos = new BufferedOutputStream(fos);
                    bytesRead = is.read(mybytearray,0,mybytearray.length);
                    current = bytesRead;
                    do {
                        bytesRead = is.read(mybytearray, current, (mybytearray.length-current));
                        if(bytesRead >= 0) current += bytesRead;
                    } while(current < FILE_SIZE);
                    bos.write(mybytearray, 0 , current);
                    bos.flush();
                    ZipFile file = new ZipFile(FILE_TO_RECEIVED) ; 
                    System.out.println(file.size()+ " zip files are received in  the client"); 
                    output = "Received"+file.size();
                    System.out.println(input+" when output is "+output);
                    pwr.println(output);
                }

                pwr.flush();
            }

        // receive file
        @SuppressWarnings("resource")
        ZipFile file = new ZipFile(FILE_TO_RECEIVED) ; 
        System.out.println(file.size()+ "in client"); 
        System.out.println("File " + FILE_TO_RECEIVED  +" has no of files "+file.size() + " downloaded (" + current + " bytes read)");
    } catch (IOException e) {
        System.out.println("Exception in Input Stream in Client");
        e.printStackTrace();
    }
    finally {
        if (fos != null){
            try {
                fos.close();
                if (bos != null) bos.close();
                if (sock != null) sock.close();
            } catch (IOException e) {
                System.out.println("Exception in closing FileOutputStream or BufferedReader or Socket");
                e.printStackTrace();
            }
        }
    }
}
public static Socket connectToServer(String server2, int socketPort) {
    Socket sock = null;
    try {
        sock = new Socket(server2, socketPort);
    } catch (IOException e) {
        System.out.println("Exception in establishing connection with server");
        e.printStackTrace();
    }
    return sock;
    }
}
public class Server 
{
    public final static int SOCKET_PORT = 13267;  
    public final static String FILE_TO_SEND = "C:/Public/Pictures/Sample Pictures.zip";  
    public static void main (String [] args ) throws IOException {
    FileInputStream fis;
    BufferedInputStream bis = null; 
    BufferedReader br;
    OutputStream os = null;
    ServerSocket servsock = null;
    PrintWriter pw;
    Socket sock = null;

    try {
        servsock = new ServerSocket(SOCKET_PORT);
        while (true) {
            System.out.println("Waiting...");
            try {
                sock = servsock.accept();
                System.out.println("Accepted connection : " + sock);  
                pw = new PrintWriter(sock.getOutputStream(), true);
                pw.println("SendZip");
                br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
                File myFile = new File (FILE_TO_SEND);
                Integer i = (int) (long) myFile.getTotalSpace();
                String input, output;
                while ((input = br.readLine()) != null) {
                     System.out.println("in while loop");
                    if(input.equals("SENDZIP"))
                     {
                         output = "SENTZIP";
                         pw.println(output);
                         System.out.println(input+ " is the input and output is "+output);
                         byte [] mybytearray  = new byte [(int)myFile.length()];
                         fis = new FileInputStream(myFile);
                         bis = new BufferedInputStream(fis);
                         bis.read(mybytearray,0,mybytearray.length);
                         os = sock.getOutputStream();
                         System.out.println("Sending " + FILE_TO_SEND + "(" + mybytearray.length + " bytes)");
                         os.write(mybytearray,0,mybytearray.length);
                         os.flush(); 
                        }
                     }
                    pw.flush();
            System.out.println("Done.");
            }
            finally {
                if (bis != null) bis.close();
                if (os != null) os.close();
                if (sock!=null) sock.close();
            }
        }
    }
    finally {
        if (servsock != null) servsock.close();
        }
    }
 }

+1使用缓冲,而不是试图一次完成整个文件。它可能适用于小文件,但不可扩展。您在服务器端和客户端看到了什么输出?@Logan有趣的一点,您能详细介绍一下这种解决方案的可扩展性吗?我是说,您的解决方案在OP不可扩展的地方是可扩展的。想象一下,尝试发送一个5GB文件并分配一个5GB的
字节[]
!如果您将文件分为2kb段的解决方案运行得很好,而且速度可能也更快,那么它将不起作用。哦,好吧,我只是误解了我的解决方案不可伸缩:)试试这个:看看您的客户机:使用
public final static int file_SIZE=6022386
是一种糟糕的文件接收方式。你传输zip文件就像传输任何其他“纯二进制”数据流一样。我在这里硬编码了文件大小,但是我有一些代码动态地获取值。。
public class Server 
{
    public final static int SOCKET_PORT = 13267;  
    public final static String FILE_TO_SEND = "C:/Public/Pictures/Sample Pictures.zip";  
    public static void main (String [] args ) throws IOException {
    FileInputStream fis;
    BufferedInputStream bis = null; 
    BufferedReader br;
    OutputStream os = null;
    ServerSocket servsock = null;
    PrintWriter pw;
    Socket sock = null;

    try {
        servsock = new ServerSocket(SOCKET_PORT);
        while (true) {
            System.out.println("Waiting...");
            try {
                sock = servsock.accept();
                System.out.println("Accepted connection : " + sock);  
                pw = new PrintWriter(sock.getOutputStream(), true);
                pw.println("SendZip");
                br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
                File myFile = new File (FILE_TO_SEND);
                Integer i = (int) (long) myFile.getTotalSpace();
                String input, output;
                while ((input = br.readLine()) != null) {
                     System.out.println("in while loop");
                    if(input.equals("SENDZIP"))
                     {
                         output = "SENTZIP";
                         pw.println(output);
                         System.out.println(input+ " is the input and output is "+output);
                         byte [] mybytearray  = new byte [(int)myFile.length()];
                         fis = new FileInputStream(myFile);
                         bis = new BufferedInputStream(fis);
                         bis.read(mybytearray,0,mybytearray.length);
                         os = sock.getOutputStream();
                         System.out.println("Sending " + FILE_TO_SEND + "(" + mybytearray.length + " bytes)");
                         os.write(mybytearray,0,mybytearray.length);
                         os.flush(); 
                        }
                     }
                    pw.flush();
            System.out.println("Done.");
            }
            finally {
                if (bis != null) bis.close();
                if (os != null) os.close();
                if (sock!=null) sock.close();
            }
        }
    }
    finally {
        if (servsock != null) servsock.close();
        }
    }
 }