Android's method of creating a simple TCP connection using socket

  • 2021-06-29 12:03:43
  • OfStack

This article provides an example of how Android creates a simple TCP connection using socket.Share it for your reference, as follows:

Communication is an important part of both Java and Android programming.Connected socket programming is naturally important.

Here, a simple demo demonstrates a basic socket programming.

Write the server first.The server side is the Java code.The author is lazy to install programming software such as eclipse, that is, direct notepad programming, dos running.Server 1 is typically an serversocket with a new binding port to listen for client requests (dead-loop listening).When a client message is received, it is read, processed, and returned to the client.The code is as follows: (more detailed comments have been made)


public class SimpleServer {
  /**
   * @param args
   * @throws IOException
   */
  public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    // Establish 1 individual ServerSocket, Used to listen on clients socket Connection Request 
    ServerSocket ss=new ServerSocket(50069);
    // Continuous acceptance of requests from clients using a loop , Server side also generates 1 individual Socket
  while(true){
  Socket s = ss.accept();
  // Receive client messages 
  BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
  System.out.println("-------------------------");
  String tt = br.readLine();
  String res = "server  Reply to you "+tt;
  System.out.println(res);
  OutputStream os=s.getOutputStream();
  os.write(res.getBytes("UTF-8"));
  System.out.println("-------------------------");
  //os.close();
  s.shutdownOutput();
  s.close();
  }
}}

The client creates a new socket bound to IP (server) and port number (same as server 1) and sends the content to the server as a stream (the send here takes care to give an end flag, such as half-off) and reads the returned content (the read here is a wait process, that is, if the server sends a message back, it reads it for a very long time,If there is no return, it will wait, which is blocked).Finally, close socket.The code is as follows:


public class MainActivity extends Activity implements Runnable{
  EditText show;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    show = (EditText) findViewById(R.id.edit1);
    MainActivity myThread = new MainActivity();
    Thread thread = new Thread(myThread);
    thread.start();
  }
  @Override
  public void run() {
    try {
      Socket socket = new Socket("192.168.145.96", 50069);
      // Set up 10 Time-out is considered after seconds 
      socket.setSoTimeout(10000);
      // Send data to server 
      OutputStream outputStream = socket.getOutputStream();
      outputStream.write("hello,server".getBytes("UTF-8"));
      socket.shutdownOutput();
      // Read data 
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String line = br.readLine();
        // Print read data 
        Log.e("MainActivity", ">>>>>>>>>>>>>>>>>>>>>>>>>" + line);
      br.close();
      socket.close();
    } catch (UnknownHostException e) {
      // TODO Auto-generated catch block
      Log.e("UnknownHost", " Data from the server ");
      e.printStackTrace();
    } catch (IOException e) {
      Log.e("IOException", " Data from the server ");
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Finally, by running the server, you can run the client to demonstrate it.

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: