KinGPinG
KinGPinG

Reputation: 171

Java Android Sockets

I'm currently working on an Android app which sends an string and a file to a java server app running on remote computer. This java server app should find the index on the file and send back the value of this index (The file structure is: index value. Example: 1 blue) The file is properly sent and received on the remote machine and I have a method which finds the value of the received index on the file. But when I'm trying to send the found value back to the phone I get an exception (closed socket), but I'm not closing the socket or any buffer. I'm not sure if the socket which is closed is the mobile app socket or the java server app socket. I'm using the same socket I use to send to receive (which is the way to work on Android). Sending the answer back to the phone is what my project is missing and is what I need help in. Here is my code:

Client app (Android app):

 private class HeavyRemProcessing extends AsyncTask<String, Void, String>
        {

            protected String doInBackground(String... urls) 
             {
                    begins = System.currentTimeMillis();

                            remoteExecution();

                ends= System.currentTimeMillis();
                procTime=ends-begins;
                aux= Long.toString(procTime);

               return aux;
             } //doInBackground() ends

            protected void onPostExecute(String time)
              {
                textView1.setText("Result: "+result+". Processing Time: "+time+" milisecs"); 
              }// onPostExecute ends

        } //HeavyRemProcessing ends


     public void executor(View view)
      {     
         key="74FWEJ48DX4ZX8LQ";

         HeavyRemProcessing task = new HeavyRemProcessing();
         task.execute(new String[] { "????" });     
      } //executor() ends


     public void remoteExecution()
        {
               // I have fixed IP and port I just deleted 
           String ip;  //SERVER IP
           int port;   // SERVER PORT 

             try
               {
                 cliSock = new Socket(ip, port);

                 file= new File("/mnt/sdcard/download/Test.txt"); 

                 long length = file.length();
                 byte[] bytes = new byte[(int) length];

                 FileInputStream fis = new FileInputStream(file);
                 BufferedInputStream bis = new BufferedInputStream(fis);
                 BufferedOutputStream out = new BufferedOutputStream(cliSock.getOutputStream());
                 BufferedReader in = new BufferedReader(new InputStreamReader(cliSock.getInputStream()));


                 int count;
                 key=key+"\r\n";
                 out.write(key.getBytes());
                 while ((count = bis.read(bytes)) > 0) 
                  {
                     out.write(bytes, 0, count);
                  }  //It works perfectly until here


                   //// PROBABLY HERE IS THE PROBLEM:               
                out.flush();
                out.close();
                fis.close();
                bis.close();                    

                result= in.readLine();  //RECEIVE A STRING FROM THE REMOTE PC


              }catch(IOException ioe)
                {
                 // Toast.makeText(getApplicationContext(),ioe.toString() +   ioe.getMessage(),Toast.LENGTH_SHORT).show();  
                } 

            }catch(Exception exp)
              {
                 //Toast.makeText(getApplicationContext(),exp.toString() +   exp.getMessage(),Toast.LENGTH_SHORT).show();               
              }   

        } //remoteExecution ends

Java Server App (Remote PC)

 public void receivingFile()
      {
         System.out.println("Executing Heavy Processing Thread (Port 8888).");

         try 
            {
                serverSocket = new ServerSocket(8888);
                InputStream is = null;
                OutputStream os= null;
                FileOutputStream fos = null;
                BufferedOutputStream bos = null;
                BufferedOutputStream boSock =null;
                DataOutputStream dataOutputStream=null;
                int bufferSize = 0;


                try 
                   {
                     socket = serverSocket.accept();  
                     System.out.println("Heavy Processing Task Connection from ip: " + socket.getInetAddress());

                   } catch (Exception ex) 
                     {
                       System.out.println("Can't accept client connection: "+ex);
                     }

                try 
                   {
                     is = socket.getInputStream();
                     dataOutputStream = new DataOutputStream(socket.getOutputStream());

                     bufferSize = socket.getReceiveBufferSize();

                   }
                     catch (IOException ex) 
                       {
                         System.out.println("Can't get socket input stream. ");
                       }

                try 
                   {
                     fos = new FileOutputStream(path);
                     bos = new BufferedOutputStream(fos);

                   }
                     catch (FileNotFoundException ex) 
                      {
                        System.out.println("File not found. ");
                      }

                byte[] bytes = new byte[bufferSize];

                int count;
                System.out.println("Receiving Transfer File!.");

                while ((count = is.read(bytes)) > 0) 
                  {
                     bos.write(bytes, 0, count);
                  }

                System.out.println("File Successfully Received!.");
                fos.close();
                bos.flush();
                bos.close();
                is.close();

                result= obj.searchIndex();
                System.out.println("Found: "+result); //This correctly print the found value

                dataOutputStream.writeUTF(result);
                dataOutputStream.flush();
                dataOutputStream.close();

                System.out.println("Data sent back to the Android Client. ");


           } catch (IOException e) 
              {
               // TODO Auto-generated catch block
               e.printStackTrace();
              }

      } // receivingFile() ends

Please if someone can help me I will really appreciate it. I'm thinking is something probably related with the buffers and the socket. My java server app throws an exception: "Closed Socket"... Thanks for your time,

Alberto.

Upvotes: 1

Views: 641

Answers (1)

Ashwin
Ashwin

Reputation: 13547

I think your problem is that you closing the outputstream before closing the inputstream. This is a bug in android. Normally in java closing outputstream only flushes the data and closing inputstream causes the connection to be closed.

But in android closing the outputstream closes the connection. That is why you are getting closed socket exception,
Put the statements

out.flush();
 out.close();

after

result=in.readLine();

or just avoid those statements(out.flush and out.close). I had also faced a similar problem. See my question

Upvotes: 1

Related Questions