I want to build a simple tcp client for Android. The client need to start by sending name and password and then maintain connection with the server till the app get closed (if we lost connection from some reason we need to re- establish connection by sending user and password).
Now i implemented some simple client like this:
public class SendRecvAsynch extends AsyncTask<String, String, TcpClient> {
final String SERVER_IP = "10.0.0.7"; //server IP address
final int SERVER_PORT = 1234;
String modifiedSentence;
EditText tv = (EditText) findViewById(R.id.editText_main);
@Override
protected TcpClient doInBackground(String... message) {
//we create a TCPClient object
try {
// create address
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
try {
//create a socket to make the connection with the server
Socket socket = new Socket(serverAddr, SERVER_PORT);
// create in out stream
DataOutputStream outToServer = new DataOutputStream(socket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// write to server and get response
outToServer.writeBytes("hello from client");
// read from server
modifiedSentence = inFromServer.readLine();
if (modifiedSentence == null)
{
modifiedSentence = "didn't get a dame thing from the server";
}
// close the socket
socket.close();
}catch (IOException e) {
tv.setText(e.toString());
e.printStackTrace();
}
} catch (UnknownHostException e) {
tv.setText("got exceptin");
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
tv.setText(modifiedSentence);
//response received from server
Log.d("test", "response " + values[0]);
//process server response here....
}
}
I start the client from OnCreate
method like this:
new SendRecvAsynch().execute("");
I expected that the app will connect the server, send him "hello from client" , wait and get the server responds and will close the socket connection.
After i get the responds i want the AsyncTask
to update an EditText
box I have on the main App screen.
The problem is that this AsyncTask
don't update the EditText
... I see in the server side that the App got connected and send the server "hello from client" but i don't see from the client side the server responds...
I guess that from some reason the background process can't get access to the main screen that belongs to the main thread, how can i change it? How can i create that simple tcp client that send and receive line from server?
Thank you.