1

Presently My Server program can able to receive the file from client socket and able to save that received file in server machine. But I am need to receive many files from client socket to server socket without closing and opening the socket connection every time.

I have written the code, this is working fine. But in this I am closing and opening the server and client socket connection in every iteration. But I need to do this without connecting and disconnecting both the sockets every time.

Please guide me seniors...


My Server code:

        int img_count=1;
        int bytesRead;
        int current = 0;
        byte [] mybytearray  = new byte [100000];

        InputStream is = null;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        Socket sock=null;

        // create socket
        ServerSocket servsock = new ServerSocket(6668);
        System.out.println("Waiting... for client req");
        int i=0;


         for ( i=0; i<9; i++)
          {

              sock = servsock.accept();        // Waiting for Client

              String fname = "Image000"+(img_count++)+".JPG";
              String fpath = "C:/RX_images/"+fname;      // Image saving path
              File myFile = new File (fpath);

              is = sock.getInputStream(); 
              fos = new FileOutputStream(myFile);
              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(bytesRead > -1);

              bos.write(mybytearray, 0 , current);

              bos.flush();
              fos.flush();
              fos.close();
              bos.close();
              is.close();
              sock.close();

          }  // End of for loop

          servsock.close();
          System.out.println("Received : "+ (i++)+ " Images");

My Client Code:

        int i=0;  
        int img_count=1;
        FileInputStream fis=null;
        BufferedInputStream bis=null;
        OutputStream os=null;
        Socket client=null;

        System.out.println("Sending...");


      for ( i=0; i<9; i++)
      {
          client = new Socket("192.168.1.54",6668);    

          String fname = "Image000"+(img_count++)+".JPG";
          String fpath = "C:/Tx_Images/"+fname;          // Image path
          File myFile = new File (fpath);

          byte [] mybytearray  = new byte [(int)myFile.length()];

          fis = new FileInputStream(myFile);
          bis = new BufferedInputStream(fis);        
          bis.read(mybytearray,0,mybytearray.length);
          os = client.getOutputStream();        
          os.write(mybytearray,0,mybytearray.length);

          bis.close();
          fis.close();
          os.flush();
          os.close();
          client.close();
          Thread.sleep(2000); 

      }   // End of for loop

      System.out.println("\n Sent : "+(i++)+" Images");

I am very new to java, Help me please....

Mars7285
  • 61
  • 1
  • 2
  • 8

3 Answers3

0

Since the socket is just a stream of bytes, in order to handle more than one file you are going to have to construct a simple protocol of some sort. In other words, the sender will have to send bytes that differentiate between the bytes in one file and the bytes in another. Since you are sending binary data, there is no series of bytes you can send to "mark" the beginning and/or/ending -- for example if you send 4 zero bytes at the end, that might be data and so the receiver cannot be sure if it's a marker or data. Two ways to handle it come to mind offhand -- break your file up into sections that are a maximum of N bytes, and send the sections one at a time. You will have to have a count of the bytes in each section, since at least one section will not have the same number of bytes as all other sections. Alternately,y you could count the bytes in the file and start with bytes that give that count, so the receiver knows how many bytes to expect. While you are giving the count, you could also give information such as the name and the type of file, if you wanted. Good luck.

arcy
  • 12,845
  • 12
  • 58
  • 103
0

This question really depends on whether you need the client to keep the connection open, or not. Typically you just need to keep the server side listening, and it's ok for the client to reconnect each time it needs to send a file.

Use an ExecutorService to keep the server side going and handle multiple connections with separate threads. Then just have the client connect and send what it needs to send and disconnect. See this question for a quick example: Multithreading Socket communication Client/Server

Also, look at how they close resources (finally) and stop the server in that example too. That is not related to your question, but you'll want to make your I/O and error handling more robust as well.

If you really do require that the server and client stay connected and send multiple files (or whatever data) then you'll need to implement some sort of a protocol as rcook notes, and you'll need to go deeper into networking and have a heartbeat and such. And, even if you do that, the client still needs to be smart enough to try to reconnect if the socket is closed, etc.

Community
  • 1
  • 1
Charlie Collins
  • 8,806
  • 4
  • 32
  • 41
  • The simpliest protocol would be sending the length of each file before the actual data. This can be easily done using DataInputStream and DataOutputStream – Rustam Miftakhutdinov Jan 13 '13 at 17:03
0

Just make simple protocol like:

 File Name\r\n
 File Size\r\n
 File Data\r\n
 File Name\r\n
 File Size\r\n
 File Data\r\n
 ....

I hope you will understand this. You can send file information initially then server will parse this file information, and make your server to read number bytes as you specified in file information. These will enable you to see file end marker and when to begin new file. BUT you must know file size before.

This will not work for data streams which have unknown length.

Make your server to read number of bytes you will be specifying, so server can know when to end file writing and begin new file or whether file is fully received before socket closes...

nullptr
  • 3,320
  • 7
  • 35
  • 68