Socket programming is a basic application of network communication. Socket technology is required to establish network communication both on the mobile side and on the PC side.
In this chapter, the small series mainly from the following aspects of the socket to introduce the relevant knowledge:
Each is "what is a socket?" What are the features of the socket? "," the difference between the socket and HTTP and TCP. " "Demo for Mobile Sockets". If you write a bad place, please criticize me.
What is a socket? The socket is also referred to as "socket". It is a way of network communication, it is not a protocol, but provides the program ape to implement TCP/IP encapsulation and transmission of data interface.
Used to establish a communication pipeline between the client and the server, so that the application/client can send requests to server/and a host through this communication pipeline, and the same time servers can correspond to establish the transfer data and exchange between the two.
In Android, we know that every application can operate with multithreading, and multiple threads of an app for network transmission can all create a socket connection. Each thread maintains its own socket pipeline, which enables concurrent network traffic.
The socket consists of 5 main components: the protocol used by the connection (TCP/UDP), the clientip,clientport number, and the server-side IP address. The port number on the server side. In Android, ServerSocket is used on the server side and the socket is used to establish a network connection, and both ends produce a socket object when the connection is successful. Second, the characteristics of the socket and the principle of communication we can see. The protocol used when a socket is established can be TCP. can also be UDP.
TCP is reliable and UDP is unreliable, because TCP requires three handshakes when it is established. The two sides establish the communication pipeline ability to transfer data, and is bidirectional.
and UDP in the transmission of data is only the application layer of data sent to packaging and attached to the destination address, not responsible for the other party is not receiving. The communication establishment of a socket can be divided into two parts: client and server.Service Side:1, create the server socket and bind to one of their own port, this port is better than 1024, because the 0~1023port number is reserved by the system, will be called by some system functions. 2. Set up the listener for the socket. Listen for other client programs to request access to the serversocket of this port. 3, if accepted, accept the request to establish the connection communication
Client:1. Create a client socket, bind the IP address and port number of the destination server you want to access2. Connect the service side (this is different from the socket connection on the PC.) No need to connect (), since Clientsocket on Android is created, assuming that the creation succeeds in calling the connection method on its own initiative3, communication with the service side4, active close Clientsocket Understanding the client and server communication process, we can understand that: the server has in fact maintained the status of listening to client requests. The socket connection can only be actively closed by the client initiating the request. At both ends of the communication, the data is implemented through InputStream and OutputStream, and first the server receives the input stream. The result is then returned to the client through the output stream.
The client side is to send the output stream first, and then receive the input stream.
The approximate mode is the following: Server and Client connection:Server listener------->client request-------> Establish connection Three, the difference between socket and HTTP, TCP must first To know that HTTP is the application layer protocol, the main solution is how to package the data. And TCP is the Transport layer protocol. The main solution is how to transfer data. Sockets are encapsulated in the TCP/IP protocol and are not themselves protocols.
The connection mode of the socket is inconsistent with the HTTP and TCP connection modes.
From the previous section has learned that the socket connection is starting from the server monitoring, and on the TCP side, the client and server connection need to go through three handshake before formally start the transmission of data, and HTTP is based on the "request-response" talent to establish the transmission of data, what does it mean? Only the first request, server talent external data, can not actively establish transmission. In the 0.9, 1.0, and 1.1 eras of HTTP, such a connection pattern can be maintained when a TCP connection is established. Respond to multiple requests.
When the socket is a package in the transport layer, the transport layer is primarily made up of TCP and UDP protocols when the socket is using the TCP protocol instead of the UDP protocol. A socket connection is actually a TCP connection. Iv. Demo Here we will create a demo to use the socket on Android.
The main function of our demo is to write a piece of text in the edit box and press the Send button. Finally, internal implementation through the socket communication mode. Feedback to the TextView to display the edited content. The details inside will be analyzed at the end. The following is an XML layout file:
Android:id= "@+id/btn_conn"/> <edittext android:layout_width= "fill_parent" android:layout_ height= "Wrap_content" android:hint= "Please edit the content to be sent here" android:id= "@+id/et_message"/> <button android:layout_width= "fill_parent" android:layout_height= "wrap_content" android:text= "send" Android:id= "@+id/btn_sent"/> <textview android:layout_width= "fill_parent" android:layout_ height= "Wrap_content" android:id= "@+id/tv" android:hint= "receive data Sent"/></linearlayout>
Layout effects such as the following:
First of all, describe the functional logic we want to achieve: 1, by clicking the connection to establish socket communication Pipeline 2, in the edit box to enter the content we want to send, press the Send button, the data will be displayed in the text control. 3, in the internal set up a thread, can not be updated in the UI thread, will cause anr;4, itself as the sender, and as the receiver, the main process is to send data package, through the outputstream for output transmission. The content is created as a message, then received by the handler, thrown into the message queue, and then decompressed when the data is processed. For UI updates. Main functions Handler.sentmessage () and Handler.handmessage (). There is outputstream and InputStream when the data packaging, encoding must be consistent.
Chinese can use GB2312.
The code is as follows:
Package Com.example.mysocketdemo;import Java.io.ioexception;import Java.io.inputstream;import Java.io.OutputStream ; Import Java.io.unsupportedencodingexception;import Java.net.socket;import Java.net.unknownhostexception;import Android.app.activity;import Android.app.actionbar;import Android.app.fragment;import Android.os.Bundle;import Android.os.handler;import Android.os.message;import Android.text.editable;import Android.view.LayoutInflater; Import Android.view.menu;import android.view.menuitem;import android.view.view;import android.view.ViewGroup; Import Android.widget.button;import Android.widget.edittext;import Android.widget.textview;import Android.widget.toast;import Android.os.build;public class Mainactivity extends Activity {private TextView tv;private Button btnsent,btnconn;private EditText ed_message;private outputstream output;private Socket clientsocket;private Handler mhandler;private MyThread Mythread;boolean stop = true; @Override protected void OnCreate (Bundle savedInstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); if (savedinstancestate = = null) {Getfragmentmanager (). BeginTransaction (). Add (R.id.containe R, New Placeholderfragment ()). commit (); } init (); Onclickevent---Connect btnconn.setonclicklistener (new View.onclicklistener () {@Overridepublic void OnClick (View V {//TODO auto-generated method stubtry {clientsocket = new Socket ("127.0.0.1", 8888);} catch (Unknownhostexception e) {/ /TODO auto-generated catch Blocke.printstacktrace ();} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} Toast.maketext (Getapplicationcontext (), "Connect OK", Toast.length_short). Show ();//Bind the socket to its own thread object try {mythread = New MyThread (Clientsocket);} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} Mythread.start ();//start thread//update UI, most of the data work has been given to the Mythread object btnsent.setenabled (tRue); btnconn.setenabled (false); stop = False;}}); Sent Message Btnsent.setonclicklistener (new View.onclicklistener () {@Overridepublic void OnClick (View v) {//TODO Auto-generated method stub//When you click the button, you get the data in the edit box and then submit it to the thread//Send the content first byte[] Msgbuffer = null;try {Msgbuffer = Ed_ Message.gettext (). toString (). GetBytes ("GB2312");} catch (Unsupportedencodingexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} After packing, add the socket output stream object try {output = Clientsocket.getoutputstream ();} catch (IOException e) {//TODO auto-generated Catch Blocke.printstacktrace ();} The try {//Output stream object writes bytes to//both the output stream and the input stream. The operation is all bytes, assuming to become a string, you need to build the String Object Output.write (Msgbuffer);} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} Toast.maketext (Getapplicationcontext (), "Send Success", Toast.length_short). Show (); Ed_message.settext ("");}}); After the data is connected and sent. The next step is to deal with the data sent to the message queue by means of messages, and then by Handl to get Mhandler = new Handler () {public void Handlemessage (AndroidOid.os.Message msg) {Tv.settext (msg.obj.toString ()); }; }; } public void Init () {TV = (TextView) Findviewbyid (r.id.tv); Btnsent = (Button) Findviewbyid (r.id.btn_sent); Ed_message = (EditText) Findviewbyid (r.id.et_message); Btnconn = (Button) Findviewbyid (r.id.btn_conn); Btnconn.setenabled (TRUE); Btnsent.setenabled (FALSE); }//define the thread class yourself; Private class MyThread extends thread{//build your own socket object to use the private socket socket within the thread; Private byte[] buf = null; Private InputStream InputStream; String str = NULL; Public MyThread (socket socket) throws IOException {this.socket = socket; InputStream = This.socket.getInputStream (); } @Override public void Run () {//TODO auto-generated method stubs while (!stop) {buf = new byte[512]; Read the data in InputStream into buf try {this.inputstream.read (BUF);} catch (IOException e) {//TODO auto-generated catch Blocke . Printstacktrace ();} try {//to make a stream of characters in the BUFParse, get this.str = new String (buf, "GB2312"). Trim (); catch (Unsupportedencodingexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} The thread acquires the InputStream byte stream from the socket, and when it is converted to a string, the thread acquires the entity content of the message//the thread will run its own mission at this time. is to create a message and send it out. Message msg = new Message (); Msg.obj = This.str; Mhandler.sendmessage (msg); }}} @Override protected void OnDestroy () {//TODO auto-generated Method stub if (mythread!=null) {Mythread.interrupt ();} Super.ondestroy (); }
After you understand the logic of the code. I'll take a second look at the whole idea:after we clicked on the connnet. will create a connection destination IP address and port socket connection, at this time, what data are not, socket OutputStream and InputStream inside are empty. Although our own defined threads are started after the connection, and the Run method must be running, there is no data to receive at this time. after we edited the writing and clicked on the Sentbutton. The text in the edit box is wrapped by a string into bytes, using the String.getbyte () method. Why, because OutputStream and InputStream only accept byte stream data.
When the socket's Getoutputstream acquires the OutputStream object, it runs the Write method for writing the data, and while the thread is still running, it suddenly discovers that there is data in the connected socket. The InputStream object was obtained using Getiuptestream, which read the byte stream using the Read method and finally packaged it into a string. once packaged into a string, the thread runs its own mission. is to encapsulate it as a message. A message queue that is plugged into the main thread in the form of a message. At this time the UI thread Messenger Hanlder is finished SendMessage task.
Finally, back to the main thread, the handler object uses the Handlmessage method to display the contents of the message on the TextView.
The above is the whole logic.
Android Network application socket (one)