SoFunction
Updated on 2025-04-05

Simple example of Socket communication transmission in Android development

This article describes the implementation method of Android Socket communication transmission. Share it for your reference, as follows:

1. Introduction to the opening

Socket is essentially a TCP protocol encapsulated by Java on the transport layer (Note: UDP uses the DatagramSocket class). To implement Socket transmission, it is necessary to build a client and a server. Additionally, the transmitted data may be strings and bytes. String transmission is mainly used for simple applications. For more complex applications (such as Java and C++ for communication), it often requires building its own application layer rules (similar to the application layer protocol) and transmitting them in bytes.

2.Socket case based on string transfer

1) Server-side code (console-based application, simulation)

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
public class Main {
  private static final int PORT = 9999;
  private List<Socket> mList = new ArrayList<Socket>();
  private ServerSocket server = null;
  private ExecutorService mExecutorService = null; //thread pool
  public static void main(String[] args) {
    new Main();
  }
  public Main() {
    try {
      server = new ServerSocket(PORT);
      mExecutorService = (); //create a thread pool
      ("The server is started...");
      Socket client = null;
      while(true) {
        client = ();
        //Put the client into the client collection        (client);
        (new Service(client)); //start a new thread to handle the connection
      }
    }catch (Exception e) {
      ();
    }
  }
  class Service implements Runnable {
      private Socket socket;
      private BufferedReader in = null;
      private String msg = "";
      public Service(Socket socket) {
         = socket;
        try {
          in = new BufferedReader(new InputStreamReader(()));
          //As long as the client connects to the server, it will send the following information to the client.          msg = "Server Address:" +() + "come toal:"
            +()+"(Send)";
          ();
        } catch (IOException e) {
          ();
        }
      }
      @Override
      public void run() {
        try {
          while(true) {
            if((msg = ())!= null) {
              // When the message sent by the client is: exit, close the connection              if(("exit")) {
                ("ssssssss");
                (socket);
                ();
                msg = "user:" + ()
                  + "exit total:" + ();
                ();
                ();
                break;
                //Receive the msg message sent by the client and then send it to the client.              } else {
                msg = () + ":" + msg+"(Send)";
                ();
              }
            }
          }
        } catch (Exception e) {
          ();
        }
      }
     /**
       * Loop through the client collection and send information to each client.
       */
      public void sendmsg() {
        (msg);
        int num =();
        for (int index = 0; index < num; index ++) {
          Socket mSocket = (index);
          PrintWriter pout = null;
          try {
            pout = new PrintWriter(new BufferedWriter(
                new OutputStreamWriter(())),true);
            (msg);
          }catch (IOException e) {
            ();
          }
        }
      }
    }
}

2) Android client code

package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
public class SocketDemo extends Activity implements Runnable {
  private TextView tv_msg = null;
  private EditText ed_msg = null;
  private Button btn_send = null;
  // private Button btn_login = null;
  private static final String HOST = "10.0.2.2";
  private static final int PORT = 9999;
  private Socket socket = null;
  private BufferedReader in = null;
  private PrintWriter out = null;
  private String content = "";
  //The receiving thread sends the information and displays it with TextView  public Handler mHandler = new Handler() {
    public void handleMessage(Message msg) {
      (msg);
      tv_msg.setText(content);
    }
  };
  @Override
  public void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    setContentView();
    tv_msg = (TextView) findViewById();
    ed_msg = (EditText) findViewById(.EditText01);
    btn_send = (Button) findViewById(.Button02);
    try {
      socket = new Socket(HOST, PORT);
      in = new BufferedReader(new InputStreamReader(socket
          .getInputStream()));
      out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
          ())), true);
    } catch (IOException ex) {
      ();
      ShowDialog("login exception" + ());
    }
    btn_send.setOnClickListener(new () {
      @Override
      public void onClick(View v) {
        // TODO Auto-generated method stub
        String msg = ed_msg.getText().toString();
        if (()) {
          if (!()) {
            (msg);
          }
        }
      }
    });
    //Start the thread and receive data sent by the server    new Thread().start();
  }
  /**
    * If the connection is abnormal, the AlertDialog will pop up!
    */
  public void ShowDialog(String msg) {
    new (this).setTitle("notification").setMessage(msg)
        .setPositiveButton("ok", new () {
          @Override
          public void onClick(DialogInterface dialog, int which) {
          }
        }).show();
  }
  /**
    * Read the information sent by the server and send it to the UI thread through the Handler
    */
  public void run() {
    try {
      while (true) {
        if (!()) {
          if (()) {
            if (!()) {
              if ((content = ()) != null) {
                content += "\n";
                (());
              } else {
              }
            }
          }
        }
      }
    } catch (Exception e) {
      ();
    }
  }
}

Analysis: In additionisCloseMethod, Socket class has anotherisConnectedMethod to determine whether the Socket object is connected successfully. When you see this name, readers may misunderstand it. In fact, the isConnected method does not determine the current connection status of the Socket object, but whether the Socket object has been connected successfully. If it has been successfully connected, even if isClose returns true now, isConnected still returns true. Therefore, to determine whether the current Socket object is in a connected state, the isClose and isConnected methods must be used at the same time, that is, the Socket object is in a connected state only when isClose returns false and isConnected returns true. Although most of the time, you can use the Socket class or the close method of the input and output stream to close the network connection, sometimes we only want to close itOutputStreamorInputStream, while closing the input and output streams, the network connection is not closed. This requires two other methods of the Socket class:shutdownInputandshutdownOutput, These two methods only turn off the corresponding input and output streams, and they do not have the function of turning off network connections at the same time. Like isClosed and isConnected methods, the Socket class also provides two methods to determine whether the input and output streams of the Socket object are closed. These two methods areisInputShutdown()andisOutputShutdown(). shutdownInput and shutdownOutput do not affect the status of the Socket object.

2. Byte-based transmission

When transferring based on bytes, you only need to convert the corresponding string and integer types into the corresponding network bytes for transmission. For details, please refer to "Detailed explanation of the relationship between Java integer number and network endianness byte[] array conversion》。

For more information about Android related content, please check out the topic of this site:Android communication methods summary》、《Android development introduction and advanced tutorial》、《Android debugging skills and solutions to common problems》、《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.