Piglet's Android starter Road Day 8 Part 6

Source: Internet
Author: User

Piglet's Android starter Road Day 8 Part 6

An analysis of Android network programming--socket network programming

--Reprint Please specify Source: Coder-pig





Introduction to this section

Finally ushered in the last section of Android Network programming: Socket programming in Android, in this section we

First, we need to introduce the concept of TCP/IP protocol and the relevant knowledge of socket, then introduce the simple socket

Process, and finally use the socket to create a simple Android chat room and socket for large file breakpoint upload

OK, start this section!



Learning Roadmap for this section:




Body:


a simple understanding of TCP/IP and sockets:





the basic flow of socket communication:




example of a simple socket network chat room:

I believe that learning Java friends in the Java network has learned to use the socket to build a simple chat room;

We first need to create a Java app as the server, and Java is the same;

Then we need to create an Android app for sending and displaying chat messages, so don't forget the following two points:

①android 4.0 is not allowed in the main thread network operation, so need to open a separate thread

② in order to ensure Android thread security, the interface changes can only be done in the main thread, or through handler, in

Call handler to send information in a child thread, call handler to complete the modification of the interface component



In order to take care of some of the Java is not familiar with friends, first write a simple socket connection server program, to familiarize everyone familiar with

The results are as follows:


The code is as follows:

Java Service side:

Server.java

Package Com.jay.pc.demo;import Java.io.bufferedwriter;import Java.io.ioexception;import java.io.OutputStreamWriter Import Java.net.serversocket;import Java.net.socket;public class Server {//define port number private static final int port = 9999;pub Lic static void Main (string[] args) {Try{serversocket server = new ServerSocket (PORT);//plug here, infinite Loop, call the Accept method, Wait for client connection while (TRUE) {Socket socket = server.accept ();//Get output stream bufferedwriter writer = new BufferedWriter (new OutputStreamWriter (Socket.getoutputstream ()));//write a string, appear in Chinese to transcode oh, otherwise there will be garbled situation writer.write (new string (" Connect to server success So, what's the problem at this point? ". GetBytes (" UTF-8 ")," GBK "); Writer.flush (); Writer.close ();}} catch (IOException e) {e.printstacktrace ();}}}

Android Client:

Activty_main.xml Layout file:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:id=" @+id/linearlayout1 "    android:layout_width=" Match_parent    " android:layout_height= "Match_parent"    android:orientation= "vertical"    tools:context= " Com.jay.example.socketdemo1.MainActivity ">    <button        android:id=" @+id/btnlogin "        android:layout _width= "Wrap_content"        android:layout_height= "wrap_content"        android:text= "Connect Server"/>        < TextView     android:layout_width= "match_parent"    android:layout_height= "match_parent"    android:id= "@ +id/txtshow "        />    </LinearLayout>




Mainactivty.java

Package Com.jay.example.socketdemo1;import Java.io.bufferedreader;import Java.io.inputstreamreader;import Java.net.socket;import Android.app.activity;import Android.os.bundle;import Android.os.handler;import Android.os.message;import Android.util.log;import Android.view.view;import Android.view.View.OnClickListener; Import Android.widget.button;import Android.widget.textview;public class Mainactivity extends Activity {private Button Btnlogin;private TextView Txtshow;private String send;//defines the IP address and port number constants private static final String HOST = "192.168.27.172"; private static final int PORT = 9999;          Define Handler Object Private Handler Handler = new Handler () {@Override//This method executes Handler when a message is sent out              public void Handlemessage (Message msg) {super.handlemessage (msg);          Handling UI Txtshow.settext (send);  }      }; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.Activity_main); btnlogin = (Button) Findviewbyid (r.id.btnlogin); txtshow = (TextView) Findviewbyid (r.id.txtshow); Btnlogin.setonclicklistener (New Acceptlistener ());} Class Acceptlistener implements view.onclicklistener{@Overridepublic void OnClick (View v) {new Thread () {public void run ( {Try{socket socket = new socket (host,port); BufferedReader br = new BufferedReader (New InputStreamReader (Socket.getinputstream ())); send = Br.readline (); Br.close ();} catch (Exception e) {e.printstacktrace ();} Handler.sendemptymessage (0);};}. Start ();}}}


Well, it is estimated that after reading the above code, the socket chat room, the approximate principle of the process has a preliminary understanding of it,

So let's continue to develop a simple chat room that can chat with multiple users at the same time! as follows:


Then open two clients, chat, run the client, the console can see the current online there are two users, and their IP


Then we open two simulator, chat, we can see two simulator are real-time chat, sent immediately after the display!

Finally, when we lose such as bye, the client will disconnect from the server, in another client can also see, such as the exit information!


Similarly, chat logs can be seen on the console console on the server side:




After reading, is not a little heart, good, next we will use code to achieve the

Service side: Server.java



Android (client)





*android using a socket to enable the continuation of large file breakpoints

We have learned to use the HTTP protocol to upload files, but the disadvantage of uploading this is that for large files

Seems a bit of a pit dad, in case of the half bang when the phone has no power off, then the next time must be re-uploaded, so it will obviously cause

User dissatisfaction (the user is very impatient), so we want to use the socket to complete the upload of large files, and add breakpoint function

And the previous multi-threaded breakpoint download a bit similar, the author level is limited, and in view of the time relationship, also do not knock out the entire program to come;

Here directly with the Preach Wisdom Podcast teacher-Li Mingwu teacher provided code, in order to facilitate everyone to master the use, will also parse the next program!

OK, so first look at the effect first!

First drag the file to upload to the SD card directory, then open the server, and then run the client, click Upload!


When the upload is complete, you can find the files we uploaded and a log file under the file path by coming to the project path of the server.


Of course, you can also go halfway down and exit the simulator, upload the file again, and verify that the breakpoint upload function is valid!


OK, let's parse the implementation code below!

Let's start with the service side!









Piglet's Android starter Road Day 8 Part 6

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.