Click here to Skip to main content
15,886,812 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
HI everyone,

Using asynctask in android, for tcp/ip connection how can i ensure client is connected or not. I have to disconnect connection using asynctask manually. Please help how to do????????????????


This is the code i used:

Java
  public class MyClientTask extends AsyncTask<void,> {

String dstAddress;
int dstPort;
String response = "";

MyClientTask(String addr, int port)
{
 dstAddress = addr;
 dstPort = port;
}

@Override
protected Void doInBackground(Void... arg0) {
  try {
  GlobalClass.socket = new Socket(dstAddress, dstPort);

  ByteArrayOutputStream byteArrayOutputStream =
                new ByteArrayOutputStream(1024);
  byte[] buffer = new byte[1024];

  int bytesRead;
  InputStream inputStream = GlobalClass.socket.getInputStream();

while ((bytesRead = inputStream.read(buffer)) != -1){
               byteArrayOutputStream.write(buffer, 0, bytesRead);
               response += byteArrayOutputStream.toString("UTF-8");
           }

 } catch (UnknownHostException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  response = "UnknownHostException: " + e.toString();
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  response = "IOException: " + e.toString();
 }finally{
  if(GlobalClass.socket != null){
   try {
    GlobalClass.socket.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
 return null;
}

and in connect button i call:
Java
MyClientTask myClientTask = new         MyClientTask(ip.getText().toString(),Integer.parseInt(port.getText().toString()));
                           myClientTask.execute();

and when required i need to disconnect the socket.....
Posted
Updated 16-Dec-14 18:14pm
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900