简体   繁体   English

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

[英]How to transfer a zip file through socket programming in java?

I am new to socket programming. 我是套接字编程的新手。 I did a simple program to transfer zip files but that is only creating an empty zip and doesn't transfer any files. 我做了一个简单的程序来传输zip文件,但这只是创建一个空的zip文件,而不传输任何文件。 Can you help me please? 你能帮我吗?

Client.java 客户端.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();
    }
  }

}

Server.java 服务器.java

package fileTransfer;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SimpleServer {

  public final static int SOCKET_PORT = 13267;  
  public final static String FILE_TO_SEND = "C:/Users/Public/Pictures/Sample Pictures.zip";  

  public static void main (String [] args ) throws IOException {
    FileInputStream fis = null;
    BufferedInputStream bis = null;
    OutputStream os = null;
    ServerSocket servsock = null;
    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);
          // send file
          File myFile = new File (FILE_TO_SEND);
          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();
          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();
    }
  }
}

Kindly help me fix this!!! 请帮我解决这个问题!!!

Try to read file in such way on client side: 尝试在客户端以这种方式读取文件:

    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();

Do the same on the server side. 在服务器端执行相同的操作。 Your InputStream will be a file and output will be a socket. 您的InputStream将是一个文件,输出将是一个套接字。 Its robust way to copy streams. 它强大的复制流方式。

I was finally able to transfer zip files through the socket. 我终于能够通过套接字传输zip文件。 Please find the code below. 请在下面找到代码。 If anyone feels that it could be made much better. 如果有人认为它可以做得更好。 Please let me know: 请告诉我:

Client.java 客户端.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;
    }
}

Server.java 服务器.java

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();
        }
    }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM