1 2 Previous Next 20 Replies Latest reply: Mar 10, 2014 11:39 AM by gimbal2 RSS

    How to send a file without closing the socket?

    Karthik Aryan

      I wrote a program to transfer a file using tcp connection, where I closed socket since the receiver need to detect the end-of--file.  But now I like to extend it to multiple file for which i should not close the socket until all the files are send. I can't find a way for this. So please help to resolve it.

        • 1. Re: How to send a file without closing the socket?
          TPD-Opitz

          Your easiest option is to simply create a separate TCP connection for each file.

           

          If you don't have that option you need to change you protokol, which means you need to change the receiver too:

          Send the length of the file before the file itself so that the receiver can count incoming bytes and interpret the next byte as the "header" of the next file.

           

          bye

          TPD

          • 2. Re: How to send a file without closing the socket?
            Karthik Aryan

            First of all thanks for your response.

             

            I can't create separate tcp connection for each file. So I tried your next suggestion but it didn't work. Is there anything to send a end of file marker through outputstream?

            • 3. Re: How to send a file without closing the socket?
              baftos

              His 'next suggestion' is sound. It should work. Your best bet is to troubleshoot why it does not work.

               

              Edit: Java provides all you need to zip and unzip files, so this may be another approach: zip-send-unzip. See the java.util.zip package.

              • 4. Re: How to send a file without closing the socket?
                TPD-Opitz

                what does that mean "it didn't work."?

                 

                bye

                TPD

                • 5. Re: How to send a file without closing the socket?
                  aksarben

                  A couple of options:

                   

                  1. Use FTP. That's what it's designed for.

                   

                  2. Send an end-of-file marker after each file. Of course, the recipient would have to know about the  EOF marker & react accordingly.

                  • 6. Re: How to send a file without closing the socket?
                    baftos

                    aksarben wrote:

                     

                    A couple of options:

                     

                    1. Use FTP. That's what it's designed for.

                     

                    2. Send an end-of-file marker after each file. Of course, the recipient would have to know about the  EOF marker & react accordingly.

                    I really don't encourage the EOF approach. It may work for this specific case and blow up if and when OP or his colleagues decide that instead of text files, they will use this protocol to send movies or music or pictures or executables... All the other approaches are better, IMHO.

                    • 7. Re: How to send a file without closing the socket?
                      TPD-Opitz

                      aksarben wrote:

                      1. Use FTP. That's what it's designed for.

                      full ack.

                      aksarben wrote:

                      2. Send an end-of-file marker after each file. Of course, the recipient would have to know about the  EOF marker & react accordingly.

                      In adition to what @baftos wrote: The receiver would have to examine each and every incomming byte for beeing the EOF maker. Does not sound like a clever plan...

                       

                      bye

                      TPD

                      • 8. Re: How to send a file without closing the socket?
                        Karthik Aryan

                        I found that when i send a file of size 5.00MB(5238429 Bytes) and I received only 4.98MB(5225407 Bytes). I have just posted my snippet please correct me if there is any error....

                         

                         

                        Sender side:

                         

                                            FileInputStream fis = new FileInputStream(myFile);

                                            BufferedInputStream bis = new BufferedInputStream(fis);

                                            OutputStream os = sock.getOutputStream();

                                            Log.i("************", "Sending...");                 

                                            byte buffer[] = new byte[1024];

                                            int read_count = 0;

                                            int offset=0;

                                            while ((read_count = bis.read(buffer, offset, buffer.length)) != -1) {

                                                os.write(buffer, 0, read_count);

                                            } 

                                            os.flush();

                                            sock.close(); 

                         

                         

                        Receiver side:

                         

                                            FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory () +"/WiFi/"+fname);

                                            BufferedOutputStream bos = new BufferedOutputStream(fos);

                                            int read_count;

                                            while((read_count=is.read(buffer, 0, 1024))!=-1)

                                            { 

                                                bos.write(buffer, offset, read_count);

                                            }

                                            bos.flush();

                                            bos.close();

                                            rd.close();

                                            sock.close();

                         

                         

                        If i send a file less than the buffer size then the control is not entering the loop in receiver side.

                        • 9. Re: How to send a file without closing the socket?
                          jschellSomeoneStoleMyAlias

                          The code that you posted does not print a count of what was sent nor a count of what was received.

                           

                          Doing that is where you start.

                          • 10. Re: How to send a file without closing the socket?
                            rp0428

                            Posting irrelevant code is just a waste of time.

                             

                            If you want help with code you need to post the code you are actually using.

                             

                            The code you posted can't possibly be what you are really using.

                             

                            1. The 'receiver' doesn't even use a socket; it reads from a file

                            2. The 'receiver' code closes two objects that the code doesn't even use:

                            rd.close(); 

                            sock.close();

                            3. None of the code shows ANY exception handling.

                            If i send a file less than the buffer size then the control is not entering the loop in receiver side.

                             

                            That should be a CLEAR indication that you have a serious flaw in your code. Fix it before continuing.

                            • 11. Re: How to send a file without closing the socket?
                              Karthik Aryan

                              I can't track where the error is occurring please help i will post the entire code........

                               

                              Sender side:

                               

                              public class ServerMainActivity extends Activity implements OnClickListener {

                                 

                                  BufferedWriter br;

                                  public static ArrayList<Socket> clients = new ArrayList<Socket>();

                                  public static ArrayList<InetAddress> iplist=new ArrayList<InetAddress>();

                                  public static ArrayList<String> cname=new ArrayList<String>();

                                  ServerSocket s;

                                  Thread ch,sf;

                                  BufferedReader bin ;

                                  PrintWriter out = null;

                                  Socket incoming;

                                  Intent inten1,inten2;

                                  String path;

                                  ch = new Thread(new ClientHandler);

                                  ch.start();

                               

                              }

                                 

                               

                               

                               

                              public class ClientHandler implements Runnable{

                               

                                      private static final int PORT_NUMBER = 5005;

                                      Socket obj;

                                      String msg;

                                      Message mssg=Message.obtain();

                                     

                                      public ClientHandler()

                                      {

                                          try {

                                              s = new ServerSocket(PORT_NUMBER);

                                          } catch (IOException e) {

                                              // TODO Auto-generated catch block

                                              e.printStackTrace();

                                          }

                                      }

                                     

                                     

                                      @Override

                                      public void run() {

                                          // TODO Auto-generated method stub

                                          System.out.println("Chat server started on port "

                                                  + PORT_NUMBER + "!");

                                          try {

                                             

                                     

                                          while(true)

                                          {

                                              incoming = s.accept();

                                              System.out.println("Checking");

                                              obj=incoming;

                                              out = new PrintWriter(new OutputStreamWriter(incoming.getOutputStream()));

                                              // inform the server of this new client

                                              if(!iplist.contains(obj.getInetAddress()))

                                              {

                                              clients.add(obj);

                                              iplist.add(obj.getInetAddress());

                                              cname.add( obj.getInetAddress().getHostName());

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

                                              Message msg = lhand.obtainMessage();

                                              Bundle bdle = new Bundle();

                                              bdle.putString("key", obj.getInetAddress().getHostName());

                                              msg.setData(bdle);

                                              lhand.sendMessage(msg);

                                               System.out.println("Client Added");

                                               sf = new Thread(new SFile(obj));

                                                  sf.start();

                                              }

                                          }

                                      }

                                      catch(Exception e)

                                      {

                                          e.printStackTrace();

                                      }

                                     

                                      }

                               

                                  }

                               

                               

                               

                               

                               

                               

                               

                               

                               

                              public class SFile implements Runnable{

                               

                                      private Socket sock;

                                      public SFile(Socket soc)

                                      {

                                          sock=soc;

                                      }

                                      @Override

                                      public void run() {

                                          // TODO Auto-generated method stub

                                          try {

                                                  File myFile = new File (path);

                                                  BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));

                                                  wr.write(myFile.getName());

                                                  wr.newLine();

                                                  wr.flush();

                                              wr.write(size(myFile.length()));

                                                  String len="&"+myFile.length()+"&";

                                                  wr.write(len);

                                                  wr.newLine();

                                                  wr.flush();

                                                  Log.i("####### file length = ", String.valueOf(myFile.length()) );

                                                  FileInputStream fis = new FileInputStream(myFile);

                                                  BufferedInputStream bis = new BufferedInputStream(fis);

                                                  OutputStream os = sock.getOutputStream();

                                                  Log.i("************", "Sending...");

                                                 

                                                  byte buffer[] = new byte[1024];

                                                  int read_count = 0;

                                                  long ch=0;

                                                  System.out.println("bl="+buffer.length);

                                                  while ((read_count = bis.read(buffer)) != -1) {

                                                      ch+=read_count;

                                                      System.out.println("ch="+ch);

                                                      os.write(buffer, 0, read_count);

                                                      os.flush();

                                                  }

                                                  bis.close();

                                                          wr.close();

                                                  sock.close();   

                                                 

                                          } catch (Exception e) {

                                              Log.i("Io execption ", "e: " + e);

                                             

                                          }

                                      }

                                     

                                  }

                               

                               

                               

                              Receiver Side:

                               

                              new Thread(new Runnable() {

                                         

                                          @Override

                                          public void run() {

                                              // TODO Auto-generated method stub

                                              try {

                                                  sock = new Socket(ip,5005);

                                                  Log.i("************", "Connecting...");

                                                  InputStream is = sock.getInputStream();   

                                                  BufferedReader rd = new BufferedReader(new InputStreamReader(is));

                                                  String fname = rd.readLine();

                                                  System.out.println("Recieved: " + fname);

                                                  String len=rd.readLine();

                                                  String flen="";

                                                  flen=len.substring(len.indexOf('&')+1, len.lastIndexOf('&'));

                                                  long fl=Long.parseLong(flen),ch=0;

                                                  System.out.println("FileSize : "+fl);                   

                                                  File folder = new File(Environment.getExternalStorageDirectory () + "/WiFi");

                                                  if(!folder.isDirectory())

                                                      folder.mkdirs();

                                                  String extra=fname;

                                                  rd.close();                   

                                                  FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory () +"/WiFi/"+fname);

                                                  BufferedOutputStream bos = new BufferedOutputStream(fos);

                                                  int read_count=0;

                                                  byte buffer[] = new byte[1024];

                                                  long start = System.currentTimeMillis();

                                                  while(ch<=fl)

                                                  {   

                                                      read_count=is.read(buffer);

                                                      ch+=read_count;

                                                      System.out.println("fl="+fl+"  ch="+ch+"  rc="+read_count);

                                                      bos.write(buffer, 0, read_count);

                                                  }

                                                  bos.flush();

                                                  System.out.println("ffl="+fl+"  fch="+ch+"  rc="+read_count);

                                                  long end = System.currentTimeMillis();

                                                  Log.i("************ end-start = ", String.valueOf(end-start));

                                                  bos.close();

                                                  sock.close();

                                                 

                                              } catch (Exception e){

                                                  Log.i("Read has IOException", "e: " + e);

                                              }

                               

                                          }

                                      }).start();

                                  }

                               

                               

                              I can't post the entire code as it depends on many classes. So please replace words wherever necessary according to you like path into some string which gives you a path of a file. Please bear with me i dont know what to do......

                              • 12. Re: How to send a file without closing the socket?
                                TPD-Opitz

                                > I can't post the entire code as it depends on many classes. So please replace words wherever necessary

                                Please remember that this is your problem, not ours. Therefore it's your task to provide an SSCCE for us.

                                 

                                bye

                                TPD

                                • 13. Re: How to send a file without closing the socket?
                                  Karthik Aryan

                                  now i have posted the code as you specified....... and also i found this link http - Java Socket InputStream read() returns -1 always, just before end - Stack Overflow , this is the exact problem faced by me. But i don't know how he got rid of that error. Now i hope you can help me....

                                   

                                   

                                  public class MainActivity extends Activity implements OnClickListener {

                                   

                                      ServerSocket s;

                                      Button b1,b2;

                                      Thread rcv,snd,sf;

                                      BufferedReader bin ;

                                      PrintWriter out = null;

                                      Socket incoming;

                                      PrintWriter rout=null;

                                      static int i=1;

                                       ObjectInputStream in=null;

                                       String smessage,msg,ip;

                                       TextView t1;

                                       static Socket sock = null,rsock=null;

                                      @Override

                                      protected void onCreate(Bundle savedInstanceState) {

                                          super.onCreate(savedInstanceState);

                                          setContentView(R.layout.activity_main);

                                          b1=(Button) findViewById(R.id.button1);

                                          b1.setOnClickListener(this);

                                          b2=(Button) findViewById(R.id.button2);

                                          b2.setOnClickListener(this);

                                          t1=(TextView) findViewById(R.id.textView1);

                                          t1.setText(null);

                                      }

                                   

                                      @Override

                                      public boolean onCreateOptionsMenu(Menu menu) {

                                          // Inflate the menu; this adds items to the action bar if it is present.

                                          getMenuInflater().inflate(R.menu.main, menu);

                                          return true;

                                      }

                                   

                                      @Override

                                      public void onClick(View arg0) {

                                          // TODO Auto-generated method stub

                                         

                                          if(arg0.getId()==R.id.button1)

                                          {

                                   

                                              new Thread(new ClientHandler()).start();

                                              t1.setText("Server Started");

                                          }

                                         

                                         

                                          if(arg0.getId()==R.id.button2)

                                          {

                                              t1.setText("Client Started");

                                  new Thread(new Runnable() {

                                             

                                              @Override

                                              public void run() {

                                                  // TODO Auto-generated method stub

                                                  try {

                                                      rsock = new Socket("192.168.137.135",5005);

                                                      Log.i("************", "Connecting...");

                                                      InputStream is = rsock.getInputStream();   

                                                      BufferedReader rd = new BufferedReader(new InputStreamReader(is));

                                                      String fname = rd.readLine();

                                                      System.out.println("Recieved: " + fname);

                                                      String len=rd.readLine();

                                                      String flen="";

                                                      flen=len.substring(len.indexOf('&')+1, len.lastIndexOf('&'));

                                                      long fl=Long.parseLong(flen),ch=0;

                                                      System.out.println("FileSize : "+fl);

                                                      File folder = new File(Environment.getExternalStorageDirectory () + "/WiFi");

                                                      if(!folder.isDirectory())

                                                          folder.mkdirs();

                                  //                    rd.close();

                                                      FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory () +"/WiFi/"+fname);

                                                      BufferedOutputStream bos = new BufferedOutputStream(fos);

                                                      int read_count=0;

                                                      byte buffer[] = new byte[1024];

                                                      long start = System.currentTimeMillis();

                                                      while(ch<=fl)

                                                      {   

                                                          read_count=is.read(buffer);

                                                          ch+=read_count;

                                                          System.out.println("fl="+fl+"  ch="+ch+"  rc="+read_count);

                                                          bos.write(buffer, 0, read_count);

                                                      }

                                                      bos.flush();

                                                      System.out.println("ffl="+fl+"  fch="+ch+"  rc="+read_count);

                                                      long end = System.currentTimeMillis();

                                                      Log.i("************ end-start = ", String.valueOf(end-start));

                                                      bos.close();

                                                      rsock.close();

                                                  } catch (Exception e){

                                                      Log.i("Read has Exception", "e: " + e);

                                                  }

                                   

                                              }

                                          }).start();

                                          }

                                      }

                                     

                                      public class ClientHandler implements Runnable{

                                   

                                          private static final int PORT_NUMBER = 5005;

                                          Socket obj;

                                          String msg;

                                         

                                          public ClientHandler()

                                          {

                                              try {

                                                  s = new ServerSocket(PORT_NUMBER);

                                              } catch (IOException e) {

                                                  // TODO Auto-generated catch block

                                                  e.printStackTrace();

                                              }

                                          }

                                         

                                         

                                          @Override

                                          public void run() {

                                              // TODO Auto-generated method stub

                                              System.out.println("Chat server started on port "

                                                      + PORT_NUMBER + "!");

                                              try {

                                                 

                                         

                                              while(true)

                                              {

                                                  incoming = s.accept();

                                                  System.out.println("Checking");

                                                  obj=incoming;

                                                  out = new PrintWriter(new OutputStreamWriter(incoming.getOutputStream()));

                                                  // inform the server of this new client

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

                                                   System.out.println("Client Added");

                                                   rcv = new Thread(new RMultiCastThread(obj));

                                                      rcv.start();

                                                      sf = new Thread(new SFile(obj));

                                                      sf.start();

                                              }

                                          }

                                          catch(Exception e)

                                          {

                                              e.printStackTrace();

                                          }

                                         

                                          }

                                   

                                      }

                                     

                                  public class RMultiCastThread implements Runnable{

                                         

                                         

                                          String lsnd="Hi",msg;

                                          Boolean threadstatus=true;

                                          private Socket incoming;

                                         

                                           public RMultiCastThread(Socket obj)

                                          {

                                               incoming=obj;      

                                          }

                                        

                                          @Override

                                          public void run() {

                                              // TODO Auto-generated method stub

                                              try

                                              {

                                                  String m;

                                              bin = new BufferedReader(new InputStreamReader(incoming.getInputStream()));

                                                           while(true)

                                                           {

                                                               m = bin.readLine();

                                                               System.out.println(m);                        

                                                           }

                                                         

                                                       } catch (Exception e) {

                                                           e.printStackTrace();

                                                           }

                                          }

                                      }   

                                     

                                  public class SFile implements Runnable{

                                   

                                      private Socket sock;

                                      public SFile(Socket soc)

                                      {

                                          sock=soc;

                                      }

                                      @Override

                                      public void run() {

                                          // TODO Auto-generated method stub

                                          try {

                                                  File myFile = new File (Environment.getExternalStorageDirectory () +"/test.txt");

                                                  BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));

                                                  wr.write(myFile.getName());

                                                  wr.newLine();

                                                  wr.flush();

                                                  String len="&"+myFile.length()+"&";

                                                  wr.write(len);

                                                  wr.newLine();

                                                  wr.flush();

                                                  Log.i("####### file length = ", String.valueOf(myFile.length()) );

                                                  FileInputStream fis = new FileInputStream(myFile);

                                                  BufferedInputStream bis = new BufferedInputStream(fis);   

                                                  OutputStream os = sock.getOutputStream();

                                                  Log.i("************", "Sending...");

                                                 

                                                  byte buffer[] = new byte[1024];

                                                  int read_count = 0;

                                                  long ch=0;

                                                  System.out.println("bl="+buffer.length);

                                                  while ((read_count = bis.read(buffer)) != -1) {

                                                      ch+=read_count;

                                                      System.out.println("ch="+ch);

                                                      os.write(buffer, 0, read_count);

                                                      os.flush();

                                                  }

                                                  bis.close();

                                                  wr.close();

                                                  sock.close();   

                                                 

                                          } catch (Exception e) {

                                              Log.i("execption ", "e: " + e);

                                             

                                          }

                                      }

                                     

                                  }

                                   

                                   

                                  }

                                   

                                   

                                   

                                  please create a text file in sdcard with the name "test.txt" and change the ip address.  before you run it

                                  • 14. Re: How to send a file without closing the socket?
                                    baftos

                                    I can only have a wild guess. One peer in this protocol is an Android device and the other one a PC, probably running Windows. It would be hard for someone here to understand the Android part, let alone run it. Therefore your code can hardly be seen as a SSCCE. I may be wrong, but I see you use BufferedReaders and BufferedWriters and the methods newLine() and readLine(). Maybe the difference comes from the line separators of Android (Unix based) and Windows?

                                    1 2 Previous Next