I want with my app to enter in the url of my server e.g. http://192.168.1.8/
and the port e.g. 1234
.
When my server receives the TCP Request message, it sends back a file (the server is already implemented).
I think that I don't need something complicated like an AsyncTask, as I do not want to keep the connection. Receiving the answer from the server, my connection must be closed.
Any indication for a way forward or a tip is highly appreciated.
Here is a simple TCP client that uses Sockets that I got working based on code in this tutorial (the code for the tutorial can also be found in this GitHub repository).
Note that this code is geared to sending strings back and forth between the client and server, usually in JSON format.
Here is the TCP client code:
Then, declare a TcpClient as a member variable in your Activity:
Then, use an AsyncTask for connecting to your server and receiving responses on the UI thread (Note that messages received from the server are handled in the
onProgressUpdate()
method override in the AsyncTask):To start the connection to your server, execute the AsyncTask:
Then, sending a message to the server:
You can close the connection to the server at any time:
Thanks for code. In my case I was having trouble receiving data, as I'm not using a line-based protocol. I wrote an alternate implementation that works with my specific server setup:
In TcpClient.java file, "run()" command you should replace with code fragment below
public void run() {
//rest of code is OK, see original
doInBackgroud in your MainActivity.java posts received message to onProgressUpdate, you can display it in other object e.g. TextView
//"response" is TextView object declared in your function
and function
protected void onCreate(Bundle savedInstanceState) { response = (TextView) findViewById(R.id.textView); //..so on