user1705850
user1705850

Reputation: 111

Android Socket does not send data

I'm trying to send a string to a server over TCP using socket and AsyncTask. String will change with the ON/OFF status of the button.

I have no error but data wont go out and I get no answer from the server. Could someone help me to understand what I'm doing wrong ?

Part of MyActivity code (interesting section comes after //Create an instance of AsyncTask):

                final MySerDeser msg = new MySerDeser();
            switch (tab_ID) {
            case 1:
                rootView = inflater.inflate(R.layout.fragment_tab1, container, false);

                //----- btn_BotolaUp
                final ToggleButton btn_BotolaUp = (ToggleButton) rootView.findViewById(R.id.btn_BotolaSu);
                btn_BotolaUp.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        String toastmessage;

                        if (isChecked) {
                            msg.serialize("datafield1", "datafield2", "datafield3", "1");
                            toastmessage = "Chiusura botola start";
                        } else {
                            msg.serialize("datafield1", "datafield2", "datafield3", "0");
                            toastmessage = "Chiusura botola stop";
                        }

                        //Create an instance of AsyncTask
                        ClientAsyncTask clientAST = new ClientAsyncTask();
                        Log.d("NetStuff" , "ClientAsyncTask");

                        //Pass the server ip, port and client message to the AsyncTask
                        clientAST.execute(new String[] { "192.168.1.100", "10000",msg.serialized });
                        Log.d("NetStuff", "clientAST.execute(new String[]...");

                        Toast.makeText(rootView.getContext(), toastmessage, Toast.LENGTH_SHORT).show();
                    }
                });

The AsyncTask code:

            /**
     * AsyncTask which handles the communication with the server
     */
    class ClientAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            String result = null;
            Log.d("NetStuff" , "String doInBackground");
            try {
                //Create a client socket and define internet address and the port of the server
                Socket socket = new Socket(params[0],
                        Integer.parseInt(params[1]));
                Log.d("NetStuff" , "Socket socket = new Socket");

                //Get the input stream of the client socket
                InputStream is = socket.getInputStream();
                Log.d("NetStuff" , "InputStream is = socket.getInputStream");

                //Get the output stream of the client socket
                PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
                Log.d("NetStuff" , "PrintWriter out = new PrintWriter");
                //Write data to the output stream of the client socket
                out.print(params[2]);
                Log.d("NetStuff", "out.print(" + params[2] + ")");
                //Buffer the data coming from the input stream
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(is));
                Log.d("NetStuff" , "BufferedReader br = new BufferedReader");
                //Read data in the input buffer
                result = br.readLine();
                Log.d("NetStuff" , "result = br.readLine()");
                //Close the client socket
                socket.close();
                Log.d("NetStuff", "socket.close");
            } catch (NumberFormatException e) {
                Log.d("NetStuff", "NumberFormatException");
                e.printStackTrace();
            } catch (UnknownHostException e) {
                Log.d("NetStuff", "UnknownHostException");
                e.printStackTrace();
            } catch (IOException e) {
                Log.d("NetStuff", "IOException");
                e.printStackTrace();
            }
            return result;
        }
        @Override
        protected void onPostExecute(String s) {
            //Write server message to the text view
            Log.d("NetStuff","Server answer:" + s);
        }
    }

Logcat is the following:

01-06 08:58:32.743 31685-31685/com.dev.netmanagement D/NetStuff: ClientAsyncTask
01-06 08:58:32.743 31685-31685/com.dev.netmanagement D/NetStuff: clientAST.execute(new String[]...
01-06 08:58:32.743 31685-31742/com.dev.netmanagement D/NetStuff: String doInBackground
01-06 08:58:32.753 31685-31742/com.dev.netmanagement D/NetStuff: Socket socket = new Socket
01-06 08:58:32.753 31685-31742/com.dev.netmanagement D/NetStuff: InputStream is = socket.getInputStream
01-06 08:58:32.763 31685-31742/com.dev.netmanagement D/NetStuff: PrintWriter out = new PrintWriter
01-06 08:58:32.773 31685-31742/com.dev.netmanagement D/NetStuff: out.print(datafield1,datafield2,datafield3,1)
01-06 08:58:32.773 31685-31742/com.dev.netmanagement D/NetStuff: BufferedReader br = new BufferedReader

Looking with wireshark, I see that no data are going out..

Looking @ logcat, it's clear that task is waiting an answer from the server. The answer will never arrive because the server has no question to answer...

Commenting following code:

     //Buffer the data coming from the input stream
                /*BufferedReader br = new BufferedReader(
                        new InputStreamReader(is));
                Log.d("NetStuff" , "BufferedReader br = new BufferedReader");
                //Read data in the input buffer
                result = br.readLine();
                Log.d("NetStuff" , "result = br.readLine()");
                */
                //Close the client socket
                socket.close();
                Log.d("NetStuff", "socket.close");

The task end and socket is closed (but still no one TCP string out from the ethernet).

Why my awful code is not transmitting ? [Help]

Upvotes: 1

Views: 2070

Answers (1)

user1705850
user1705850

Reputation: 111

[SOLVED] Thanks to greenapps, I add out.flush() and all is now working.

So, if you need to send TCP data declare following class:

    /**
    * AsyncTask which handles the communication with the server
    */
    class ClientAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            String result = null;
            try {
                //Create a client socket and define internet address and the port of the server
                Socket socket = new Socket(params[0],
                        Integer.parseInt(params[1]));

                //Get the input stream of the client socket
                InputStream is = socket.getInputStream();

                //Get the output stream of the client socket
                PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
                //Write data to the output stream of the client socket
                out.print(params[2]);
                out.flush();
                //Buffer the data coming from the input stream
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(is));
                //Read data in the input buffer
                result = br.readLine();
                //Close the client socket
                socket.close();
            } catch (NumberFormatException e) {
                e.printStackTrace();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }
        @Override
        protected void onPostExecute(String s) {
            //Write server message to the text view
            Log.d("NetStuff","Server answer:" + s);
        }
    }

And call task with:

//Create an instance of AsyncTask
ClientAsyncTask clientAST = new ClientAsyncTask();
//Pass the server ip, port and client message to the AsyncTask
clientAST.execute(new String[]{"192.168.1.100", "10000", "message to send"});

Great !

Upvotes: 1

Related Questions