Android Socket Communication Detailed _android

Source: Internet
Author: User

Brief introduction of socket communication

There are two main modes of communication between Android and Server, one is HTTP communication and the other is socket communication. The biggest difference between the two is that the HTTP connection uses a "request-response" approach, where the connection channel is established at the request, and the server can return the data to the client after the client sends a request to the server. While the socket communication is to establish a connection after the two sides can directly carry out data transmission, in connection with the implementation of the information of the active push, and do not need every time the client wants to send the server request. So, what is a socket? Socket, also known as sockets, in the program to provide a communication with the outside port, that is, port communication. By establishing the socket connection, it can provide the channel for the data transmission of both sides of communication. The main features of the socket are low data loss rate, easy to use and easy to transplant.

1.1 What is a socket socket

is an abstraction layer through which applications can send and receive data, and sockets allow applications to be added to the network to communicate with other applications on the same network. In short, the socket provides a port for the program to communicate with the outside world and provides a data transfer channel for both sides of the communication.

Classification of 1.2Socket

Depending on the underlying protocol, the socket is implemented in a variety of ways. This guide describes only the contents of the TCP/IP protocol family, where the main socket type is a stream socket (streamsocket) and a datagram socket (datagramsocket). Stream sockets offer TCP as its End-to-end protocol, which provides a reliable word throttling service. Datagram sockets use the UDP protocol to provide data packaging and delivery services. Next, let's take a look at the basic implementation model for both types of sockets.

Basic communication model of Socket

Three, the basic principle of socket implementation

3.1 Socket based on TCP protocol

The server side first declares a ServerSocket object and specifies the port number, and then calls the ServerSocket accept () method to receive the client's data. The Accept () method is in a blocked state where no data is received. (Socketsocket=serversocket.accept ()) to read the received data through InputStream once the data is received.

The client creates a socket object that specifies the server-side IP address and port number (Socketsocket=newsocket ("172.168.10.108", 8080), and reads the data through the InputStream. Gets the data sent by the server (Outputstreamoutputstream=socket.getoutputstream ()), and the last data to be sent is written to the OutputStream to perform the socket data transfer of the TCP protocol.

3.2 Data transmission based on UDP protocol

The server side first creates a Datagramsocket object and directs the listening port. Next, create an empty Datagramsocket object to receive the data (bytedata[]=newbyte[1024;] Datagramsocketpacket=newdatagramsocket (data,data.length)), use the Datagramsocket receive method to receive data sent by the client, Receive () is similar to ServerSocket's Accepet () and is in a blocked state where no data is received.

The client also creates a Datagramsocket object and directs the listening port. Next, create a InetAddress object that resembles the sending address of a network (inetaddressserveraddress=inetaddress.getbyname) ("172.168.1.120" ). Define a string to send, create a Datagrampacket object, and develop the address and port number to which the datagram packet is sent to the network, and finally send the data using the Send () of the Datagramsocket object. * (stringstr= "Hello"; Bytedata[]=str.getbyte ();D atagrampacketpacket=new datagrampacket (Data,data.length, serveraddress,4567); socket.send (packet);

Four, Android to achieve simple socket communication

Introduction: Add Permissions

<!--allows 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"/>
<!--allows 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 network-->
<uses-permission android:name= "Android.permission.INTERNET"/>

4.1 Communication using TCP protocol

Android-side implementation:

 protected void Connectserverwithtcpsocket () {socket socket; 
       try {//Create a Socket object and specify the IP and port number for the service port = new Socket ("...",); 
       Create a InputStream user to read the file to send. 
       InputStream InputStream = new FileInputStream ("E://a.txt"); 
       The OutputStream object that gets the socket is used to send data. 
       OutputStream outputstream = Socket.getoutputstream (); 
       Creates a byte buffer byte array for the read local file byte buffer[] = new byte[*]; 
       int temp =; Loop read file while (temp = inputstream.read (buffer)!=-) {//write data to Ouputstream object Outputstrea 
       M.write (buffer, temp); 
  
       //Send the Read data to the service End Outputstream.flush (); 
 /** or create a message, use BufferedWriter write, see your requirements **///String socketdata = "[; fjks;]"; 
 BufferedWriter writer = new BufferedWriter (new OutputStreamWriter (//Socket.getoutputstream ())); 
 Writer.write (Socketdata.replace ("\ n", "") + "\ n"); 
       Writer.flush (); /****************/} catch (Unknownhostexception e) {e.printstacktrace (); 
     catch (IOException e) {e.printstacktrace (); } 
  
   }

Server-side Simple implementation:

public void Serverreceviedbytcp () { 
   //declares a ServerSocket object 
   serversocket serversocket = null; 
   try { 
     //Create a ServerSocket object and let this socket listen on the port 
     serversocket = new ServerSocket (); 
     Call the ServerSocket accept () method, accept the request sent by the client, 
     //If the client does not send the data, then the thread will stall without continuing the 
     socket socket = serversocket.accept (); 
     From the socket to get InputStream object 
     inputstream inputstream = Socket.getinputstream (); 
     byte buffer[] = new byte[*]; 
     int temp =; 
     Read the data sent by the client while 
     (temp = inputstream.read (buffer)!=-) {System.out.println (InputStream) ( 
       new String ( buffer, temp); 
    } 
    Serversocket.close (); 
  } catch (IOException e) { 
     e.printstacktrace (); 
   } 
 

4.2 Communication using UDP protocol

The client sends the data implementation:

 protected void Connectserverwithudpsocket () {datagramsocket socket; try {//Create the Datagramsocket object and specify a port number, note that if the client needs to receive the return data from the server,//also need to use this port number to receive, so be sure to remember the socket = new Datag 
    Ramsocket (); 
     Use InetAddress (inetaddress). Getbyname converts the IP address to the network address inetaddress serveraddress = Inetaddress.getbyname ("...");  
     InetAddress serveraddress = (inetaddress) inetaddress.getbyname ("..."); String str = "[; fjks;]";  
     /Set the message to send byte data[] = Str.getbytes ()//Convert string str string to byte array create a Datagrampacket object for sending data. Parameter one: The data parameter to send two: the length parameter of the data three: the network address parameter of the service end: Server end port number datagrampacket packet = new Datagrampacket (data, data.length, serve  
     Raddress,);  
   Socket.send (packet);//Send the data to the server. 
   catch (SocketException e) {e.printstacktrace (); 
   catch (Unknownhostexception e) {e.printstacktrace (); 
   catch (IOException e) {e.printstacktrace (); }  
 } 

Data returned by the client receiving server:

public void Receiveserversocketdata () { 
   datagramsocket socket; 
   The try { 
     //instantiated port number is consistent with the socket when it is sent, otherwise the data 
     socket = new Datagramsocket () is not received; 
     byte data[] = new byte[*]; 
     Parameter one: The data parameters to accept two: the length of the data 
     datagrampacket packet = new Datagrampacket (data, data.length); 
     Socket.receive (packet); 
     Converts the received data to string string result 
     = new string (Packet.getdata (), Packet.getoffset (), 
         packet.getlength ()); 
     Socket.close ()//Not used remember to close 
     System.out.println ("The number of reveived Socket is:" + flag 
         + "Udpdata:" + result ); 
   } catch (SocketException e) { 
     e.printstacktrace (); 
   } catch (IOException e) { 
     e.printstacktrace (); 
   } 
 

Server Receive client implementation:

 public void Serverreceviedbyudp () { 
   //Create a Datagramsocket object and specify the listening port. (UDP uses datagramsocket)  
   datagramsocket socket; 
   try { 
    socket = new Datagramsocket (); 
     Creates an array of byte type for storing the received data  
     byte data[] = new byte[*];  
    Creates a Datagrampacket object and specifies the size of the Datagrampacket object  
     datagrampacket packet = new Datagrampacket (data,data.length);  
     Read received data  
     socket.receive (packet);  
     Converts the data sent by the client to a string.  
     //Use a string method with three parameters. Parameter one: Packet parameter two: starting position parameter three: packet length string result  
     = new string (Packet.getdata (), Packet.getoffset (), packet.getlength ());  
   catch (SocketException e) { 
     e.printstacktrace (); 
   } catch (IOException e) { 
    e.printstacktrace (); 
   }  
 

The above content is small to share the Android socket communication of the relevant knowledge, I hope you like.

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.