1

This is my first app on android and I'm trying to write a TCP client.

So far, I have a python TCP server and I tested it with python TCP client and it works fine.

I took the TCP client example from here.

When I start the app, I can see on wireshark the handshake so the connection was established.

Now, the problem is with sending message. when I put the function call

if (mTcpClient != null) 
{
   mTcpClient.sendMessage("testing");
}

in the main activity:

public void ChangeButtonState(View view) 
{
    boolean state = ((ToggleButton) view).isChecked();
    if (state) 
     {

        if (mTcpClient != null) {
            mTcpClient.sendMessage("testing");
        }


        textView.setText("button is on. sent Tcp message. ");
        textView.setVisibility(View.VISIBLE);
    } else {
        textView.setText("button is off");
    }
}

The code crashes on the line mBufferOut.println(message); in TcpClient class.

But if I call that function right after the line mBufferOut = new PrintWriter(socket.getOutputStream()); in TcpClient class, the client transmit the message, the server receives it and sends it back to client.

So my question is why is the code crashing? the mTcpClient member is not null.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
user1673206
  • 1,671
  • 1
  • 23
  • 43

1 Answers1

1

You should send network requests in a background thread. Use AsyncTask or Thread.

new Thread(new Runnable(){
    public void run(){
        mTcpClient.sendMessage("test");
    }
}).start();
Nabin Bhandari
  • 15,949
  • 6
  • 45
  • 59
  • 1
    Thanks! solved the problem. why should it be on thread anyway? – user1673206 Oct 11 '17 at 13:49
  • 1
    Glad I could help. If you send network requests in the foreground thread, the app will freeze till the request is completed. So the android SDK has forced the developers to perform network calls in a background thread. – Nabin Bhandari Oct 11 '17 at 14:11