簡體   English   中英

如何通過Java中的套接字編程傳輸zip文件?

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

我是套接字編程的新手。 我做了一個簡單的程序來傳輸zip文件,但這只是創建一個空的zip文件,而不傳輸任何文件。 你能幫我嗎?

客戶端.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();
    }
  }

}

服務器.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();
    }
  }
}

請幫我解決這個問題!!!

嘗試在客戶端以這種方式讀取文件:

    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文件。 請在下面找到代碼。 如果有人認為它可以做得更好。 請告訴我:

客戶端.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;
    }
}

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