简体   繁体   English

Android Socket不发送数据

[英]Android Socket does not send data

I'm trying to send a string to a server over TCP using socket and AsyncTask. 我正在尝试使用套接字和AsyncTask通过TCP将字符串发送到服务器。 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 ): 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();
                    }
                });

The AsyncTask code: 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 is the following: 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

Looking with wireshark, I see that no data are going out.. 看着wireshark,我发现没有数据流出。

Looking @ logcat, it's clear that task is waiting an answer from the server. 看起来@ logcat,很明显,任务正在等待服务器的答复。 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). 任务结束和套接字已关闭(但仍然没有一个TCP字符串从以太网输出)。

Why my awful code is not transmitting ? 为什么我的糟糕代码无法传输? [Help] [救命]

[SOLVED] Thanks to greenapps, I add out.flush() and all is now working. [已解决]感谢greenapps,我添加了out.flush(),现在一切正常。

So, if you need to send TCP data declare following class: 因此,如果您需要发送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);
        }
    }

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 ! 太好了!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM