2

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. Can you help me please?

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

}

Server.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!!!

user1395264
  • 143
  • 3
  • 18
  • Try this: http://stackoverflow.com/questions/4687615/how-to-achieve-transfer-file-between-client-and-server-using-java-socket?rq=1 Look at your client: usage of `public final static int FILE_SIZE = 6022386;` is terrible way to receive files. – Xupypr MV Aug 18 '14 at 11:55
  • 1
    You'd transfer a zip file like you'd transfer any other "pure binary" data stream. – Hot Licks Aug 18 '14 at 11:55
  • I have hard coded the file size here but then I have some code that takes the value dynamically .. – user1395264 Aug 29 '14 at 09:25

2 Answers2

3

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. Its robust way to copy streams.

Antoniossss
  • 31,590
  • 6
  • 57
  • 99
  • +1 use buffering instead of trying to do the whole file in one go. It will likely work for small files but it isn't scalable. – ldam Aug 18 '14 at 11:37
  • What output do you see on the server side and on the client side? – Greycon Aug 18 '14 at 11:52
  • @Logan Interesting point, could you elaborate about scalability of such solution? – Antoniossss Aug 18 '14 at 12:16
  • 1
    I'm saying your solution is scalable where OP's is not. Imagine trying to send a 5GB file and allocating a `byte[]` of 5GB! It would not work, where your solution of chunking the file into 2kb segments works perfectly and is likely faster too. – ldam Aug 18 '14 at 12:39
  • oh, ok I just missundestood that my solution is not scalable:) – Antoniossss Aug 18 '14 at 12:57
3

I was finally able to transfer zip files through the socket. Please find the code below. If anyone feels that it could be made much better. Please let me know:

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

Server.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();
        }
    }
 }
eltabo
  • 3,749
  • 1
  • 21
  • 33
user1395264
  • 143
  • 3
  • 18