How do I send data to a socket server that has already been started within an Asynctask?

Asked

Viewed 107 times

1

I was able to connect to the server through the application, receive and show the data sent by it. There is also no problem 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 to and print what the server says:

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 fix this and can help me, I am most grateful.

1 answer

1


I managed to solve the problem, only need to create a saidaServidor visible to the whole class with private PrintStream saidaServidor and create a method to be called on onClick button you want to send the data of a editText, for example. I declared the method as follows, within Asynctask:

public void enviarParaServidor(String s){
    saidaServidor.println(s);
}

Hence, after you have already run and started the server with the Asynctask call, it is easy to call the method to send the data to the server by taking a String from anywhere, including a editText, as follows: instaciaDoObjetoDaClasseQueHerdaAsyncTask.enviarParaServidor(string_vinda_de_qualquer_lugar). In my case, the instantiated object is class ConexaoSocket and is called cs, in addition, I take the data of a editText. Therefore, within the onClick of the button, my code was the following:

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

I hope I helped someone, ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.