How do I send data to a socket server that was already started inside an AsyncTask?

1

I have already been able to connect to the server by the application, receive and display the data sent by it. There are also no problems sending messages to the server. The problem is: once the connection is established, capture data from an editText and send that data to the server that was opened in AsyncTask.

Class I use to open the connection, listen and print what the server sends:

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

        @Override
        protected Void doInBackground(String... args) {
            try {
                Socket servidor = new Socket("192.168.0.20", 3232);
                try {
                    PrintStream saidaServidor = new PrintStream(servidor.getOutputStream());
                    Scanner s = new Scanner(servidor.getInputStream());

                    while (s.hasNextLine()) {
                        publishProgress(s.nextLine());
                    }
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                servidor.close();
            }catch (Exception e){
                e.printStackTrace();
                System.out.println("Erro: "+e.getMessage());
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(String... s) {
            if(s.length > 0){
                txvRetornoSocket.setText(s[0]);
            }
        }
    }

If anyone has any idea how to solve this and can help me, I am very grateful.

    
asked by anonymous 08.01.2017 / 02:59

1 answer

1

I was able to solve the problem, you only have to create a saidaServidor visible for the whole class with private PrintStream saidaServidor and create a method to be called in the onClick of the button that wants to send the data of a editText , for example. I declare the method as follows, within AsyncTask:

public void enviarParaServidor(String s){
    saidaServidor.println(s);
}
Then, after running and starting the server with the AsyncTask call, you can easily call the method to send the data to the server, taking a String from anywhere, including a editText , as follows: instaciaDoObjetoDaClasseQueHerdaAsyncTask.enviarParaServidor(string_vinda_de_qualquer_lugar) . In my case, the instantiated object is of class ConexaoSocket and is called cs , in addition, I get the data of a editText . So, within the onClick of button, my code looks like this:

cs.enviarParaServidor(editText.getText().toString());

I hope I have helped someone, ;)

    
08.01.2017 / 04:26