Android Socket不发送数据

时间:2016-01-06 16:35:22

标签: java android sockets

我正在尝试使用socket和AsyncTask通过TCP向服务器发送字符串。 字符串将随按钮的ON / OFF状态而变化。

我没有错误,但数据不会出来,我得不到服务器的回答。 有人能帮助我理解我做错了吗?

MyActivity代码的一部分(有趣的部分出现在//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();
                    }
                });

AsyncTask代码:

            /**
     * 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如下:

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

与wireshark一起看,我发现没有数据出来..

看@logcat,很明显任务正在等待服务器的回答。 答案永远不会到来,因为服务器没有问题要回答......

评论以下代码:

     //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");

任务结束和套接字已关闭(但仍然没有一个TCP串从以太网输出)。

为什么我糟糕的代码没有传输? [说明]

1 个答案:

答案 0 :(得分:1)

[解决] 感谢greenapps,我添加了.flush(),现在一切正常。

因此,如果您需要在类之后发送TCP数据声明:

    /**
    * 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);
        }
    }

用以下方式调用任务:

//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"});

太棒了!