SoFunction
Updated on 2025-03-02

Android implements the method of receiving data by TCP client

This article describes the method of Android implementing the TCP client to receive data. Share it for your reference, as follows:

Used with log4net to receive debugging information. Therefore, this client only receives string data through TCP and then displays it on the interface.

Receive TCP data

try {
  Socket s = new Socket("192.168.1.5", 8240);
  InputStream inputStream = ();
  DataInputStream input = new DataInputStream(inputStream);
  byte[] b = new byte[10000];
  while(true)
  {
    int length = (b);
    String Msg = new String(b, 0, length, "gb2312");
    ("data",Msg);
  }
}catch(Exception ex)
{
  ();
}

Open thread to perform the receiving operation

However, if the receiving code is directly placed in the UI button to handle the event, a NetworkOnMainThreadException will be directly raised, because the Socket operation cannot be performed in the main thread. Here, use AsyncTask to open another thread to perform socket operations.

// Activity button eventGetLogTask task = new GetLogTask();
(null);
// Nested classes in Activity classpublic class GetLogTask extends AsyncTask<Void,Void,String>
{
  @Override
  protected String doInBackground(Void...param){
      try {
      Socket s = new Socket("192.168.1.5", 8240);
      InputStream inputStream = ();
      DataInputStream input = new DataInputStream(inputStream);
      byte[] b = new byte[10000];
      while(true)
      {
        int length = (b);
        String Msg = new String(b, 0, length, "gb2312");
        ("data",Msg);
      }
    }catch(Exception ex)
    {
      ();
    }
    return "";
  }
}

AsyncTask communicates with interface threads

1. The interface needs to start and pause TCP reception operations.
The interface thread uses () to notify the receiving thread to end the receiving operation.
The receiving thread calls isCancelled() in doInBackground to check whether the end reception requirement occurs.

2. After AsyncTask receives the data, it is passed to the interface to display.

The receiving thread uses the Handler to pass data to the interface
If you use Handler, the data is passed to the interface for processing as a "message".
Handler includes the function of processing messages and publishing messages. Here, processing messages is to display the log text on the interface, and the interface threads do it. Posting a message means taking the log text as a parameter, calling the postmessage function, and receiving threads to do it.

Processing messages in the main thread

Handler handler = new Handler(){
  @Override
  public void handleMessage(Message msg){
    (().toString()+(String));
  }
};

Receive the post message in the thread

Message msg = new Message();
 = msgstring;
().();

The above constitutes a simple but available TCP log receiver. Take a 360wifi or Xiaomiwifi and you can use your mobile phone to receive the logs sent by the PC application.

For more information about Android related content, please check out the topic of this site:Android communication methods summary》、《Android debugging skills and solutions to common problems》、《Android development introduction and advanced tutorial》、《Android multimedia operation skills summary (audio, video, recording, etc.)》、《Summary of the usage of basic Android components》、《Android View View Tips Summary》、《Android layout layout tips summary"and"Android control usage summary

I hope this article will be helpful to everyone's Android programming design.