1

Hi Stackoverflow members! Heres my issue... 1) Connect To a TCP Server *CHECK 2) Send the Initial Packet & Receive from Server (VB.NET) *CHECK

NOW MY ISSUE

I'm trying to keep my connection alive, and continue to listen for incoming data. I tried using a timer but I had no luck. any help would be highly highly appreciated

  package com.WheresmySon;


  import java.io.BufferedReader;
  import java.io.BufferedWriter;
  import java.io.IOException;
  import java.io.InputStreamReader;
  import java.io.OutputStreamWriter;
  import java.net.Socket;
  import java.net.UnknownHostException;
  import android.app.Activity;
  import android.content.Intent;
  import android.os.AsyncTask;
  import android.os.Bundle;
  import android.util.Log;
  import android.view.View.OnClickListener;
  import android.widget.TextView;
  import java.util.Timer;
  import java.util.TimerTask;


  public class TcpClient extends Activity {
private static BufferedReader in;
private static BufferedWriter out;
private static Socket s;


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    new TcpClientTask().execute();

}


class TcpClientTask extends AsyncTask<Void, Void, Void> {
    private static final int TCP_SERVER_PORT = 1234;
    private boolean error = false;
    Boolean SocketStarted = false;

    protected Void doInBackground(Void... arg0) {
        try {
            s = new Socket("10.0.2.2", TCP_SERVER_PORT);


                in = new BufferedReader(new InputStreamReader(s.getInputStream()));
                out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));

            //send output msg
            String outMsg = "VER:Android,LAT:28.111921,LNG:-81.950433,ID:1038263,SND:0,VDO:0,TXT:Testing";
            out.write(outMsg);
            out.flush();

            Log.i("TcpClient", "sent: " + outMsg);

            //accept server response

            String inMsg = in.readLine();

            Log.i("TcpClient", "received: " + inMsg);



            //close connection
        } catch (UnknownHostException e) {
            error = true;
            e.printStackTrace();
        } catch (IOException e) {
            error = true;
            e.printStackTrace();
        } 

        return null;
    }

    protected void onPostExecute() {
        if(error) {
            // Something bad happened

        }
        else {
            // Success

    }
}

}

//replace runTcpClient() at onCreate with this method if you want to run tcp client as a service
private void runTcpClientAsService() {
    Intent lIntent = new Intent(this.getApplicationContext(), TcpClientService.class);
    this.startService(lIntent);
}

  }

TcpClientService.java

 package com.WheresmySon;

 import java.io.BufferedReader;
 import java.io.BufferedWriter;
      import java.io.IOException;
 import java.io.InputStreamReader;
 import java.io.OutputStreamWriter;
 import java.net.Socket;
 import java.net.UnknownHostException;

 import android.app.Service;
 import android.content.Intent;
      import android.os.IBinder;
 import android.util.Log;

 public class TcpClientService extends Service {

@Override
public IBinder onBind(Intent arg0) {
    return null;
}
@Override
public void onCreate() {
    runTcpClient();
    this.stopSelf();
}
private static final int TCP_SERVER_PORT = 1234;
private void runTcpClient() {
    try {
        Socket s = new Socket("10.0.2.2", TCP_SERVER_PORT);
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        //send output msg
        String outMsg = "TCP connecting to " + TCP_SERVER_PORT + System.getProperty("line.separator"); 
        out.write(outMsg);
        out.flush();
        Log.i("TcpClient", "sent: " + outMsg);
        //accept server response
        String inMsg = in.readLine() + System.getProperty("line.separator");
        Log.i("TcpClient", "received: " + inMsg);
        //close connection
        s.close();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } 
     }
 }

1 Answers1

1

AsyncTask is not the best place for any network stuff, especially for non-statless connections like Sockets. Best approach is to use Service. You could try to search for any code example about how to use Services to handle socket connection in Android. This code will never works fine.

Evos
  • 3,915
  • 2
  • 18
  • 21
  • Hi Evos. If you look at the bottom of the code there is a runTCPClientAsService() Should I use that instead? – Ruben Pizarro Dec 12 '12 at 07:19
  • If this is an example project, and it already has correct implementation of `TcpClientService`, yes it better to use it instead of `AsyncTask`. – Evos Dec 12 '12 at 07:22
  • Evo. Here is the TcpClientServer() lets say I use this how would I go about "Listening" for data coming in and keep this connection open as a Service? – Ruben Pizarro Dec 12 '12 at 07:26
  • @Ruben this is very big question and it includes a lot of information about programming and using Android framework. First of all check documentation about Services (https://developer.android.com/guide/components/services.html) and if you are not proficient in Android you could try to use it in a simple way like int this tutorial (http://thinkandroid.wordpress.com/2010/03/27/incorporating-socket-programming-into-your-applications/) – Evos Dec 12 '12 at 07:33