Simple examples of Android TCP communications and frequently asked questions [timeout/main thread blocking]

Source: Internet
Author: User
Tags flush readline

Individuals prefer to look at examples, starting with the simplest, step-by-step testing.

Let's put aside the theory and run the program again. Only run up, will have the power to continue to learn, penetrate the entire code of the operating mechanism.


The objective of this case is --

Simulation of a PC server and the Android side of the communication, the goal is to be as streamlined as possible, so that the code left only the core parts needed to reduce the difficulty of reading notes code.

--------------------------

> "instance"

The code for the server on the PC:

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


Import Java.net.Socket; public class Socketserver {//Listener port 12345     private static final int port = 12345      &nbsp ;   public static void main (string[] args) {          try {        &NBSP ;     SYSTEM.OUT.PRINTLN ("Waiting for Client");               ServerSocket serversocket = new ServerSocket (PORT);               Socket clientsocket = serversocket.accept ();
              SYSTEM.OUT.PRINTLN ("Client Online");             while (true) {                 // Loop Monitor client request                   try {            & nbsp        //Get input stream &nbsp                     BufferedReader in = new BufferedReader (New Inputstre Amreader (Clientsocket.getinputstream ()));                      //Get information from client         &NB Sp             String msg = In.readline ();              &NBS P       SYSTEM.OUT.PRINTLN ("Client message:" +msg);                  } catch (IOException e) {        &NBSP ;             SYSTEM.OUT.PRINTLN ("Read and write error");                       e.printstacktrace ();                  } finally {            &NBSP ;
  Serversocket.close ();                     ClienTsocket.close ();                     SYSTEM.OUT.PRINTLN ("Server shutdown");
                      break;
                           }             } catch (Exception e) {              SYSTEM.OUT.PRINTLN ("End Mouth is occupied ");               e.printstacktrace ();          }      }  

from this we can see that the server is built mainly by the following steps:

1. Set up the socket of the server and set up a listening port

ServerSocket serversocket = new ServerSocket (PORT);

2. ServerSocket the server to the socket on the client: (When not set, will always block.) You can try.

Socket clientsocket = serversocket.accept ();

Because of the need for circular listening, the action to get the message should be placed in a while loop:

3. Get the abstract class of the input stream from the Clientsocket on the client, then instantiate and read and write.

BufferedReader in = new BufferedReader (New InputStreamReader (Clientsocket.getinputstream ()));
 String msg = In.readline ();

client code on Android:

@Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
        Setcontentview (R.layout.activity_main);     
        Button b= (button) Findviewbyid (R.id.button);
                B.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {
    The new thread (net). Start ();  Runnable net=new Runnable () {@Override public void run () {try {Socket
                Socket
                Socket=new socket ("192.168.1.102", 12345);//Note here socket = new socket ();
                SocketAddress socaddress = new Inetsocketaddress ("192.168.1.102", 12345);
                Socket.connect (socaddress, 3000);/timeout 3 seconds/message sent to the service String msg = "Good Night"; try {//Get output stream and instantiate bufferedwriter out = new BufferedWriter (new OutputStreamWriter (s) Ocket. Getoutputstream ());
                Out.write (msg+ "\ n");//Prevent Sticky packs out.flush (); What happens if you don't add this flush.
                catch (Exception e) {e.printstacktrace ();
                    Finally {//close socket socket.close ();
                SYSTEM.OUT.PRINTLN ("Client shutdown");
                The catch (Exception e) {System.out.println ("link error");
            E.printstacktrace (); }
        }
    };
from there, you can see that the client is built with the following steps:

1. Create the socket socket for the client itself:

Socket = new socket ();

2. Establish a connection (I know this is not the same as code, you may have doubts, but please look down)

Socket = new socket (ip,port);

3. Send message:

BufferedWriter out = new BufferedWriter (New OutputStreamWriter (Socket.getoutputstream ()));
Out.write (msg);
Out.flush ()//What will happen if you don't add this flush.
4. Close Client Socket:
Socket.close ();


Now, the TCP communication function for Android is far from complete, but fast, don't worry, go on looking down:

Observe the above Android client code. Again, how do you use the relevant client code in the activity? Why do I write a thread to do network operation?

A: Since 4.0, Android has not allowed network-related operations in the main thread. The reason for this design is that, due to the network delay, uncertainties and other factors, and the socket itself in the socket is in the blocking state, if the main thread in the network-related operations, will cause the entire app is seriously blocked.

Therefore, from 4.0, any attempt to perform a network operation in the main thread will result in an exception that throws a "android.os.NetworkOnMainThreadException".

So how do we solve it?

Create a child thread, so you'll see the following in the code I give:

    Runnable net=new Runnable () {
        @Override public
        void Run () {
           //network Operation
        }}
    }
When you use it, just let the runnable start:
New Thread (NET). Start ();


You may notice at this point that I instantiated the socket at the client and did not use what most people often wrote:

Socket=new Socket ("192.168.1.102", 12345);
It's written like this:

Socket = new socket ();
SocketAddress socaddress = new Inetsocketaddress ("192.168.1.102", 12345);
Socket.connect (socaddress, 3000);/timeout 3 seconds
Why, then? We know that when the socket is disconnected, it will always be blocked, and because the socket itself is not instantiated, you cannot set the timeout for the socket. This often leads to the line Cheng Ka the Lord for a long time, and finally throws error110 (Time_out).

I write this, can artificially set the timeout time, also easy to do multiple timeout replay.

In addition, Android has a lot to do with permissions, and some models or system versions don't allow your app to use the Internet at all. Then we need to add the following content to the permissions:

    <!--allow applications to change network status-->
    <uses-permission android:name= "Android.permission.CHANGE_NETWORK_STATE"/>
    <!--allows applications to change WIFI connection status-->
    <uses-permission android:name= "Android.permission.CHANGE_WIFI_STATE"/ >
    <!--allow applications to access related network information-->
    <uses-permission android:name= "android.permission.ACCESS_NETWORK_ State "/>
    <!--allow applications to access the network information of the WiFi network card-->
    <uses-permission android:name=" Android.permission.ACCESS_WIFI_STATE "/>
    <!--allows applications to fully use the network-->
    <uses-permission android:name=" Android.permission.INTERNET "/>
    <uses-permission android:name=" Android.permission.WAKE_LOCK "/>"

You can now test this instance. If you still can't connect your PC server successfully, then look down.


------------------------

> "Wrong line"

From the wrong point of view, we need to do is from the server and the client two aspects of the error.

First, we should make sure that the servers and ports are fine.

Open the server in Eclipse, then enter cmd and enter talent localhost 12345.

If successful, Eclipse's console will output "client is online."

Then we test the IP of the PC server entered when the Android client connects: (IP and port values please determine for yourself)

Reboot the server and enter the cmd input talent 192.168.1.102 12345.

If this step succeeds, but your Android client is still unable to connect to your PC server, I would like to ask you to check your Windows Firewall settings below.

Control Panel \ System and Security \ Windows Firewall-> Advanced Settings-> Inbound rules to see if these items are blocked by the firewall:

Now test your client again to see if you can connect to the server. Most of the sample code timeout problem (error:110) can be solved here.


If not, we will then test the Android client.

First, make sure your phone gives you the app permission.

Next, please check the port value you have set, is not under 1024, or use the common software and the value of the sensitive port. If yes, please change it to 12345 and test again.

Basically, to this step, as long as the compiler did not error, the operation is correct, in the Android version has not changed greatly in the case, can already connect to the server.


----------------------

> "theory"

Examples combined with the foundation, here found a few theoretical articles of the big hand, you can refer to me to give this small example, and then further study:


implementation and generalization of the Android UDP communication:

http://blog.csdn.net/shenpibaipao/article/details/70237697

java input and output flow detailed:

http://blog.csdn.net/zsw12013/article/details/6534619

Socket Communication principle (the Android client and server are interoperable in TCP&&UDP mode):

http://blog.csdn.net/mad1989/article/details/9147661



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.