Android How to create a simple TCP connection using the socket _android

Source: Internet
Author: User
Tags readline stub

This article illustrates how Android uses the socket to create a simple TCP connection. Share to everyone for your reference, specific as follows:

Both in Java and in Android programming, communication is an important part of it. Have connected socket programming, the importance of nature is unquestionable.

Here is a simple demo demo one of the most basic socket programming.

First write the service side. The server side is Java code. I am too lazy to install Eclipse and other programming software, is directly Notepad programming, DOS operation. The service side is typically a new binding port ServerSocket, listening for client requests (dead loop sniffing). When a client message is received, the message is read, processed, and then returned to the client. The code is as follows: (more detailed comments are available)

public class Simpleserver {
   * @param args
   * @throws ioexception
  /public static void main ( String[] args) throws IOException {/
    /TODO auto-generated Method Stub
    //Create a ServerSocket to monitor connection requests for client sockets
    serversocket ss=new ServerSocket (50069);
    Using loops to accept requests from clients, the server side also generates a socket while
  (true) {
  socket s = ss.accept ();
  Receive client message
  bufferedreader br = new BufferedReader (New InputStreamReader (S.getinputstream ()));
  System.out.println ("-------------------------");
  String TT = Br.readline ();
  String res = "Server replied to your" +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 is a new socket that binds the IP (server) and port number (as well as the server). The content is then sent to the server in the form of a stream (the sending note here gives the end sign, such as a half shutdown), and reads the postback (the read here is a wait process, that is, for a long time, If the server sends back a message, it reads, and then waits, or blocks, without sending back. Close the socket at the end. 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
    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 ("", 50069);
      10 seconds after setting is considered to be timeout 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 the data read to LOG.E ("Mainactivity", ">>>>>>>>>>>>>>>>>>>>>>>>> "+ line);
      Br.close ();
    Socket.close ();
      catch (Unknownhostexception e) {//TODO auto-generated catch block log.e ("Unknownhost", "Data from server");
    E.printstacktrace ();
      catch (IOException e) {log.e ("IOException", "Data from server");
    TODO auto-generated Catch block E.printstacktrace ();


Finally, to run the server, you can run the client for demonstration.

For more information on Android-related content readers can view the site topics: "The Android Communication method Summary", "Android Debugging techniques and common problem solving method summary", "Android Development introduction and Advanced Course", "Android Multimedia operation tips Summary (audio, Video, audio, etc.), "Summary of Android Basic components usage", "Android View Overview", "Android Layout layout skills Summary" and "Android Control usage Summary"

I hope this article will help you with the Android program.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.