java - 使用 TCP + AsyncTask 保持连接打开并监听从服务器发送的数据

标签 java android android-intent android-asynctask inputstreamreader

您好 Stackoverflow 成员(member)!这是我的问题... 1) 连接到 TCP 服务器 *检查 2) 发送初始数据包并从服务器接收 (VB.NET) *CHECK

现在是我的问题

我正试图保持我的连接,并继续监听传入的数据。我尝试使用计时器,但我没有运气。任何帮助将不胜感激

  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();
    } 
     }
 }

最佳答案

AsyncTask 不是处理任何网络内容的最佳场所,尤其是对于 Sockets 等非静态连接而言。最好的方法是使用 Service。您可以尝试搜索有关如何在 Android 中使用服务处理套接字连接的任何代码示例。此代码永远无法正常工作。

关于java - 使用 TCP + AsyncTask 保持连接打开并监听从服务器发送的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13834516/

相关文章:

android - ViewModel、LiveData 和 Transformations.map

Android TextView 数字动画

iphone - OpenGL ES : getting a fixed size for an object

android - 以编程方式发送 SMS Android(未接收状态)

android - 使用一个特定应用程序在视频捕获中打开相机的 adb 命令是什么?

java - 带有 WindowListener 的 JDialog - 未触发 windowClosing

java - 将数据传递到主 Activity 时尝试写入空数组错误

java - 是否可以 "intercept"复制/剪切/粘贴操作并将其替换为我自己的代码?

java - 如何一键关闭两个 Activity ?

java - guice:在命令行运行时注入(inject)/绑定(bind)