0

这是我的情况(在真实设备上,而不是模拟器上):
我有一个App_A,它通过 TCP 将一些数据流式传输到另一个可能是同一设备上的App_B的软件。
App_A用户手册中,据说可以将数据流式传输到同一设备上的另一个应用程序(本例中为App_B ),只需通过App_A中提供的选项将destination_IP 更改为“localhost”并将destination_port 更改为“8888” 。
因此,数据流是从App_a最后到App_B

在这种情况下,我将 App_B 开发为一个 TCP 客户端应用程序,用于侦听设备上的任何流式 TCP 数据。

这是我写的代码(在网上找到):

主要活动

public class MainActivity extends AppCompatActivity {

  TcpClient mTcpClient;
  Context context;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      context = this;
      new ConnectTask().execute("");
  }


  public class ConnectTask extends AsyncTask<String, String, TcpClient> {

      @Override
      protected TcpClient doInBackground(String... message) {

        //we create a TCPClient object
        mTcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
            @Override
            //here the messageReceived method is implemented
            public void messageReceived(String message) {
                //this method calls the onProgressUpdate
                publishProgress(message);
            }
        });
        mTcpClient.run();

        return null;
      }

      @Override
      protected void onProgressUpdate(String... values) {
          super.onProgressUpdate(values);
          //response received from server
          Toast.makeText(context, "Ricevo "+values[0], Toast.LENGTH_LONG).show();
          Log.e("test", "response " + values[0]);
          //process server response here....

      }
  }
}

TCP_CLIENT

public class TcpClient {

  public static final String SERVER_IP = "localhost";
  public static final int SERVER_PORT = 8888;

  private String mServerMessage;
  private OnMessageReceived mMessageListener = null;

  private boolean mRun = false;
  private PrintWriter mBufferOut;
  private BufferedReader mBufferIn;


  public TcpClient(OnMessageReceived listener) {
      mMessageListener = listener;
  }

  public void sendMessage(String message) {
      if (mBufferOut != null && !mBufferOut.checkError()) {
          mBufferOut.println(message);
          mBufferOut.flush();
      }
  }

  public void stopClient() {

      mRun = false;

      if (mBufferOut != null) {
          mBufferOut.flush();
          mBufferOut.close();
      }

      mMessageListener = null;
      mBufferIn = null;
      mBufferOut = null;
      mServerMessage = null;
  }

  public void run() {

      mRun = true;

      try {
        InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

        Log.e("TCP Client", "C: Connecting...");

        try (Socket socket = new Socket(serverAddr, SERVER_PORT)) {

            //sends the message to the server
            mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

            //receives the message which the server sends back
            mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));


            //in this while the client listens for the messages sent by the server
            while (mRun) {

                mServerMessage = mBufferIn.readLine();

                if (mServerMessage != null && mMessageListener != null) {
                    //call the method messageReceived from MyActivity class
                    mMessageListener.messageReceived(mServerMessage);
                }

            }

            Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + mServerMessage + "'");

        } catch (Exception e) {

            Log.e("TCP", "S: Error", e);

        }
        //the socket must be closed. It is not possible to reconnect to this socket
        // after it is closed, which means a new socket instance has to be created.


      } catch (Exception e) {

          Log.e("TCP", "C: Error", e);

      }

  }

  public interface OnMessageReceived {
      public void messageReceived(String message);
  }

 } 

我的问题是,我在 Socket 构造函数中作为第一个参数放置的每个值(在 TcpClient 类 > 运行方法 > 尝试资源语句中),它都会引发以下异常:
java.net.ConnectException: failed to connect to localhost/127.0.0.1 (port 8888): connect failed: ECONNREFUSED (Connection refused)

我试图写下所有的语句,但我无法解决这个问题:
try (Socket socket = new Socket("localhost", SERVER_PORT)) ....
try (Socket socket = new Socket("127.0.0.1", SERVER_PORT)) ....
try (Socket socket = new Socket(InetAddress.getByName(SERVER_IP), SERVER_PORT)) ....
try (Socket socket = new Socket(InetAddress.getLocalHost(), SERVER_PORT)) ....

我读到只有当我需要访问模拟器上的本地主机时,本地主机 IP 必须是“10.0.2.2”,这不是我的情况。无论如何,我也在设备上尝试了这个选项,但它不起作用,并且抛出了带有 ETIMEDOUT(连接超时)的 ConnectException。

我知道我的代码没有针对这种情况进行优化,但目前我只关心 TCP 通信是否正常工作,而不关心性能问题。
我会请求你的帮助,如果你能帮助我,我将不胜感激。

4

0 回答 0