A simple way to learn how to use an Android socket _android

Source: Internet
Author: User
Tags stub

This knowledge is not isolated, which has about, socket programming, multithreading operations, and I/O flow operations. Of course, there are more than one way to achieve this, it is just one of them, give the same novice a little thought. If you have any recommendations, please advise!
First of all, let's look at the interface of the application, you can basically know the approximate function.

Activity_main.java

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http:// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:o" rientation= "Vertical" tools:context= ". Mainactivity "> <edittext android:id=" @+id/edittext "android:layout_width=" Match_parent "Android:layout_" height= "wrap_content" android:hint= "Please enter the content to send"/> <button android:id= "@+id/button01" android:layout_width= " Match_parent "android:layout_height=" wrap_content "android:text= connection"/> <button android:id= "@+id/button02" and
 Roid:layout_width= "Match_parent" android:layout_height= "wrap_content" android:text= "Send"/> <ScrollView Android:layout_width= "Match_parent" android:layout_height= "wrap_content" android:scrollbars= "Vertical" Android: Fadingedge= "vertical" > <textview android:id= "@+id/textview" android:layout_width= "Match_parent" Android:layo ut_height= "wrap_content" android:text= "Output information:"/&GT

 </ScrollView> </LinearLayout>

The interface is very simple.

Below we need a server, and a client. Server, I'm using the Java server that eclipse writes, and the client, I'm using Android studio to write it.

Package com.ryan.socketdemo01;
Import Android.os.Handler;
Import Android.os.Message;
Import android.support.v7.app.AppCompatActivity;
Import Android.os.Bundle;
Import Android.util.Log;
Import Android.view.Menu;
Import Android.view.MenuItem;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.EditText;
Import Android.widget.TextView;

Import Android.widget.Toast;
Import java.io.IOException;
Import Java.io.OutputStream;
Import java.io.UnsupportedEncodingException;

Import Java.net.Socket; /** * This example function: The client sends data to the client (dynamic output data) */public class Mainactivity extends appcompatactivity implements View.onclicklisten
 er{private Button button01 = null;
 Private Button button02 = null;
 Private EditText edittext = null;

 Private TextView TextView = null;
 private static Socket clientsocket = null;
 Private byte[] Msgbuffer = null;


 Handler Handler = new Handler ();
 private void Initview () {Button01 = (Button) Findviewbyid (R.ID.BUTTON01); BUTTON02 = (Button) findViewbyid (R.ID.BUTTON02);
 EditText = (edittext) Findviewbyid (R.id.edittext);

 TextView = (TextView) Findviewbyid (R.id.textview);
 Button01.setonclicklistener (this);

 Button02.setonclicklistener (this);
 Button01.setenabled (TRUE);
 Button02.setenabled (FALSE);
 } @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
 Setcontentview (R.layout.activity_main);

 Initview (); @Override public void OnClick (View v) {switch (V.getid ()) {case R.ID.BUTTON01://TODO:15-9-4 Socket Connection Thread CO
  Nnectthread ();
  Break
  Case R.ID.BUTTON02://todo:15-9-4 Send data thread sendmsgthread ();
 Break
 } private void Sendmsgthread () {final String text = Edittext.gettext (). toString ();
 try {msgbuffer = text.getbytes ("UTF-8");
 catch (Unsupportedencodingexception e) {e.printstacktrace ();
   New Thread (New Runnable () {@Override public void run () {try {outputstream outputstream; Socket output Stream outputstream = Clientsocket.gEtoutputstream ();
   Outputstream.write (Msgbuffer);
   Outputstream.flush ();
  Outputstream.close ();
  catch (IOException e) {e.printstacktrace ();
   Handler.post (New Runnable () {@Override public void run () {Textview.append (Sent successfully: +text+ "\ n");
  }
  });
 }). Start (); private void Connectthread () {New Thread (new Runnable () {@Override public void run () {try {Clientsocket
   = new Socket ("10.0.2.2", 9001); if (clientsocket.isconnected ()) {Handler.post (new Runnable () {@Override public void run () {Textview.appen D ("Connection successful!")
    "+" \ n ");
    Button01.setenabled (FALSE);
    Button02.setenabled (TRUE);
   }
   }); }else {handler.post () {new Runnable () {@Override public void run () {Textview.append connection failed!
    "+" \ n ");
   }
   });
  } catch (IOException e) {e.printstacktrace ();
 }}). Start ();

 }
 @Override Public
 Boolean oncreateoptionsmenu (Menu menu) {
 //inflate the menu; This adds items to the Action bar I F it is present.
 Getmenuinflater (). Inflate (R.menu.menu_main, menu);
 return true;
 }

 @Override Public
 Boolean onoptionsitemselected (MenuItem item) {
 //Handle Action Bar item clicks here. The action Bar would
 //automatically handle clicks on the Home/up button, so long
 //As you specify a parent acti Vity in Androidmanifest.xml.
 int id = item.getitemid ();

 Noinspection simplifiableifstatement
 if (id = = r.id.action_settings) {return
  true;
 }

 return super.onoptionsitemselected (item);
 }


The way my threads are used here are:

New Thread (new Runnable) {
 @Override public
 Void Run ()} 
} 

Some people on the internet said that this way is very low, and not good, but now I will only this, even asynctask also in the study.

Also, the method by which a child thread updates the main UI:

I am using the handler.post (); It's also a very simple way to use.

Handler Handler = new Handler (); 

Handler.post (New Runnable () {
   @Override public
   void Run () {
   textview.append ("Sent successfully:" +text+ "\ n");
   }
  );
 

For a few seed threads to update the main UI, I'll write another blog later. I have now known no less than 4 of the methods, not in situ operations.

And here's how I'm going to do the I/O stream operation:

Here I do not do detailed introduction, everybody oneself google! What, you won't google? Find FQ Tools Yourself ~ ~

Here I'm talking about my simple use of I/O.

Everything begins with the original, Inputstream,outputstream, his method only reader () and write (). On top of that, for example what uses the most BufferedReader objects, is the upgrade package on top of it, wearing a dress, become more gorgeous just. His technical terminology is--decorator mode, interested in can go over the information.

At first, my approach to InputStream and OutputStream was not very clear, and it was often wrong to use the Write () method on the InputStream. I do not know where to see such a phrase, I/O flow operation is relative to the socket,serversocket connected with the data flow pipeline, reader and write is read and write meaning, is relative to that data flow pipeline operation. That is, read the information in the pipeline and write the information to the pipeline. I don't know.

The last is the socket we want to learn.

His use is also very simple, set up a socket object, set IP and port, get its I/O stream.

Clientsocket = new Socket ("10.0.2.2", 9001);

OutputStream = Clientsocket.getoutputstream ();

There are so many basic ways to use it here.

Tell me about the problems I've encountered here:

1. The emulator connection to the Java server is not connected. IP settings are not correct, I started to set the IP is 127.0.0.1. Resolved connection:

Http://stackoverflow.com/questions/8191192/reaching-a-network-device-by-ip-and-port-using-the-android-emulator /8191487#8191487

Http://stackoverflow.com/questions/10336637/how-do-i-socket-an-android-program-to-a-localhost-server

2. Forget to set the manifest, or the system provides Android.permission.INTERNET is all capitalized!! Funny to say, but I just encountered such a problem, the system automatically completed code hints, all uppercase, I think that is the case, the result should be lowercase.

<uses-permission android:name= "Android.permission.INTERNET"/>

Forget to put the code on the Java server and fill it up.

/**
 * This instance function: Accept the data sent from the server/public
class Main {public

  static void Main (string[] args) {
    //TODO auto-g enerated method Stub
    New Serverlistener (). Start ();
  }

}

 Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import java.io.UnsupportedEncodingException;
Import Java.net.ServerSocket;

Import Java.net.Socket;


Import Javax.swing.JOptionPane;
  public class Serverlistener extends thread{private Socket clientsocket = null;
  Private ServerSocket serversocket = null;
  Private InputStream InputStream = null;
  
  Private byte[] buffer = NULL; @Override public void Run () {//TODO auto-generated Method stub try {serversocket = new Serversocke
      T (9001);
      System.out.println ("Port is open, waiting to connect ~ ~");
      Block clientsocket = Serversocket.accept ();
      SYSTEM.OUT.PRINTLN ("Existing user connection");
      
      InputStream = Clientsocket.getinputstream ();
      BufferedReader br = new BufferedReader (new InputStreamReader (InputStream));
      
      String str;
      while (str = Br.readline ())!= null) {System.out.println (str); }}catch(IOException e)
    {//TODO auto-generated catch block E.printstacktrace ();
        }finally{try {inputstream.close ();
      Serversocket.close ();
      catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();

 }
    }
    
    
  }

}

This is the data received on the server side:

OK, that's basically it.

The above is the entire content of this article, I hope to help you learn.

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: info-contact@alibabacloud.com 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.