Android-based socket communication

Source: Internet
Author: User

I. INTRODUCTION of SOCKET COMMUNICATION

There are two main ways of communication between Android and Server, one is HTTP communication, the other is socket communication. The biggest difference between the two is that the HTTP connection uses "request-response mode", which is to establish a connection channel on request, and the server can return the data to the client after the client sends a request to the server. and the socket communication is to establish a connection between the two can be directly transmitted data, the connection can realize the active push of information, and do not need each time by the client to send a request to the server. So, what is a socket? Socket, also known as socket, within the program provides a port to communicate with the outside world, that is, port communication. By establishing a socket connection, a channel can be provided for transmitting data from both sides of the communication. The main features of the socket are low data loss rates, simple to use and easy to migrate.

1.1 What is a socket socket
is an abstraction layer through which applications send and receive data, using sockets to add applications to the network and communicate with other applications that are on the same network. Simply put, the socket provides a port within the program that communicates 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 types are stream sockets (Streamsocket) and datagram Sockets (Datagramsocket). The stream socket provides a trustworthy byte-stream service for TCP as its end-to-end protocol. Datagram sockets use the UDP protocol to provide data packaging and delivery services. Let's take a look at the basic implementation model of these two socket types.

Second, Socket basic communication model

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 ServerSocket's accept () method to receive the client's data. The Accept () method is stuck in a blocked state without data being received. (Socketsocket=serversocket.accept ()), once the data is received, the received data is read by InputStream.
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 InputStream, Gets the data emitted by the server (Outputstreamoutputstream=socket.getoutputstream ()), and finally writes the data to be sent to the OutputStream for 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 port to listen. Next, create an empty Datagramsocket object to receive the data (bytedata[]=newbyte[1024;] Datagramsocketpacket=newdatagramsocket (Data,data.length)) to receive data sent by the client using Datagramsocket's Receive method, Receive () is similar to ServerSocket's Accepet () in a blocked state where no data is received.
The client also creates a Datagramsocket object and directs the listening port. Next, create an InetAddress object that resembles the sending address of a network (Inetaddressserveraddress=inetaddress.getbyname ("172.168.1.120") ). Defines a string to send, creates a Datagrampacket object, and formulates the address and port number to which the datagram packet is sent to the network, and finally sends 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 implementation socket simple communication

Preface: Adding Permissions

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

4.1 Communication using TCP protocol

Android-side implementations:

 protected voidConnectserverwithtcpsocket () {socket socket; Try{//create a Socket object and specify the IP and port number of the serverSocket =NewSocket ("192.168.1.32",1989); //Create a InputStream user to read the file to be sent. InputStream InputStream =NewFileInputStream ("E://a.txt"); //gets the socket's OutputStream object for sending data. OutputStream OutputStream =Socket.getoutputstream (); //creates a buffer byte array of type Byte to hold the read local file            byteBuffer[] =New byte[4*1024x768]; inttemp =0; //Looping through Files             while(temp = inputstream.read (buffer))! =-1) {                  //write data to the Ouputstream objectOutputstream.write (Buffer,0, temp); }              //send the Read data to the serverOutputstream.flush (); /** or create a message, use BufferedWriter to write, see your needs **/  //String socketdata = "[2143213;21343fjks;213]"; //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 voidserverreceviedbytcp () {//declares a ServerSocket objectServerSocket ServerSocket =NULL; Try {          //Create a ServerSocket object and let the socket listen on port 1989ServerSocket =NewServerSocket (1989); //call the Accept () method of ServerSocket, accepting the request sent by the client,//If the client does not send the data, then the thread will stall and not continueSocket socket =serversocket.accept (); //get the InputStream object from the socketInputStream InputStream =Socket.getinputstream (); byteBuffer[] =New byte[1024x768*4]; inttemp =0; //read the data sent by the client from the InputStream         while(temp = inputstream.read (buffer))! =-1) {System. out. println (NewString (Buffer,0, temp));      } serversocket.close (); } Catch(IOException e) {e.printstacktrace (); }  }  

4.2 Communication using UDP protocol

The client sends the data implementation:

protected voidConnectserverwithudpsocket () {datagramsocket socket; Try {          //Create a Datagramsocket object and specify a port number, note that if the client needs to receive the return data from the server,//You also need to use this port number to receive, so be sure to rememberSocket =NewDatagramsocket (1985); //use InetAddress (inet4address). Getbyname to convert the IP address to a network addressInetAddress serveraddress = Inetaddress.getbyname ("192.168.1.32"); //inet4address serveraddress = (inet4address) inet4address.getbyname ("192.168.1.32"); String str ="[2143213;21343fjks;213]";//set the message to be sent        byteData[] = Str.getbytes ();//Converting a string str string to a byte array//creates a Datagrampacket object that is used to send data. //parameter one: The data parameter to be sent two: the length parameter of the data three: server side of the network address parameter four: Servers port port numberDatagrampacket packet =NewDatagrampacket (data, data.length, ServerAddress,10025); Socket.send (packet);//send data to the server. }Catch(SocketException e) {e.printstacktrace (); } Catch(unknownhostexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }    }  

The client receives the data returned by the server:

 Public voidReceiveserversocketdata () {datagramsocket socket; Try {          //the port number that is instantiated is the same as the socket that was sent, or the data is not receivedSocket =NewDatagramsocket (1985); byteData[] =New byte[4*1024x768]; //parameter one: to accept the data parameter two: the length of dataDatagrampacket packet =Newdatagrampacket (data, data.length);          Socket.receive (packet); //converts received data to string stringString result =NewString (Packet.getdata (), Packet.getoffset (), packet.getlength ()); Socket.close ();//don't use the remember to closeSystem. out. println ("The number of reveived Socket is:"+Flag+"Udpdata:"+result); } Catch(SocketException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }  }  

The server receives the client implementation:

 Public voidserverreceviedbyudp () {//creates a Datagramsocket object and specifies the listening port. (UDP uses Datagramsocket)datagramsocket socket; Try{Socket=NewDatagramsocket (10025); //Create an array of type byte to hold the received data        byteData[] =New byte[4*1024x768]; //creates a Datagrampacket object and specifies the size of the Datagrampacket objectDatagrampacket packet =NewDatagrampacket (data,data.length); //read the Received datasocket.receive (packet); //converts the data sent by the client to a string. //A string method that uses three parameters. Parameter one: Packet parameter two: starting position parameter three: packet lengthString result =NewString (Packet.getdata (), Packet.getoffset (), packet.getlength ()); } Catch(SocketException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }    }  

Five, Summary:

The use of UDP to the Android side and server-side reception can be seen, in fact, the Android and server side of the transmission and reception of the large court, as long as the port number is correct, mutual communication there is no problem, TCP uses the way the stream is sent, UDP is sent in the form of packets.

Demo Address: http://download.csdn.net/detail/mad1989/5626975

Android-based socket communication

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.