Android Implement Method for TCP Client to Receive Data

  • 2021-06-29 12:04:24
  • OfStack

This article gives an example of how Android implements TCP client to receive data.Share it for your reference, as follows:

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

Receive TCP data


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

Open thread for receive operation

However, if the receive code is placed directly in the UI button to handle the event, NetworkOnMainThreadException will be raised directly because the Socket operation cannot be performed in the main thread.AsyncTask is used here to open another thread to perform the socket operation.


// Activity In Button Event 
GetLogTask task = new GetLogTask();
task.execute(null);
// Activity Nested Classes in Classes 
public 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 = s.getInputStream();
      DataInputStream input = new DataInputStream(inputStream);
      byte[] b = new byte[10000];
      while(true)
      {
        int length = input.read(b);
        String Msg = new String(b, 0, length, "gb2312");
        Log.v("data",Msg);
      }
    }catch(Exception ex)
    {
      ex.printStackTrace();
    }
    return "";
  }
}

AsyncTask communicates with interface threads

1. The interface needs to start and pause the TCP receive operation.
The interface thread uses AsyncTask.cancel() to notify the receiving thread to end the receive operation.
The receiving thread calls isCancelled () in doInBackground to check for an end receive request.

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

Receiving thread uses Handler to pass data to interface
With Handler, the data is passed to the interface as a "message".
Handler includes functions for handling and publishing messages.Here, processing messages is done by displaying log text on the interface, which is done by the interface thread.Publishing a message takes the log text as a parameter, calls the postmessage function, and receives a thread to do so.

Processing messages in the main thread


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

Receive Publish Messages from Threads


Message msg = new Message();
msg.obj = msgstring;
(MainActivity.this).handler.postMessage();

The above constitutes a simple but available log receiver in TCP mode.Get a 360wifi or millet wifi and use your mobile phone to receive the log from the pc application.

More readers interested in Android-related content can view the site's topics: Summary of Android Communication, Summary of Android Debugging Skills and Frequently Asked Questions, Introduction to Android Development and Advanced Tutorials, Summary of Android Multimedia Operating Skills (Audio, Video, Recording, etc.), Summary of Usage of Android Basic Components, Summary of Android View View Skills, andAndroid Layout layout Skills Summary and Android Control Usage Summary

I hope that the description in this paper will be helpful to everyone's Android program design.


Related articles: