Here is a simple TCP client that uses the Sockets I worked with based on the code for this lesson (the lesson code can also be found in this GitHub repository ).
Please note that this code is designed to send strings between the client and server, usually in JSON format.
Here is the TCP client code:
import android.util.Log; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; public class TcpClient { public static final String TAG = TcpClient.class.getSimpleName(); public static final String SERVER_IP = "192.168.1.8";
Then declare TcpClient as a member variable in your Activity:
public class MainActivity extends Activity { TcpClient mTcpClient;
Then use AsyncTask to connect to the server and receive responses in the user interface stream (note that messages received from the server are processed in an override of the onProgressUpdate() method in AsyncTask):
public class ConnectTask extends AsyncTask<String, String, TcpClient> { @Override protected TcpClient doInBackground(String... message) {
To establish a connection to your server, run AsyncTask:
new ConnectTask().execute("");
Then, by sending a message to the server:
//sends the message to the server if (mTcpClient != null) { mTcpClient.sendMessage("testing"); }
You can close the connection to the server at any time:
if (mTcpClient != null) { mTcpClient.stopClient(); }
Daniel Nugent
source share