Basic implementation method of socket communication in Android development _java

Source: Internet
Author: User
Tags stub

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);

Three, the simplest socket communication implementation example on Android
Server programs

The server program needs to run on the PC, the program is simpler, so there's no need to build an Android project, define a Java class directly, and run the class. It only establishes ServerSocket listening and uses a socket to get the input output stream.

Import java.io.IOException;
Import Java.io.OutputStream;
Import Java.net.ServerSocket;
Import Java.net.Socket;

public class Simpleserver {

  /**
   * @param args
   * @throws ioexception
  /public static void main ( String[] args) throws IOException {/
    /TODO auto-generated Method Stub

    //Create a ServerSocket to monitor connection requests for client sockets
    ServerSocket ss=new ServerSocket (30000);
    Using loops to accept requests from clients, the server side also generates a socket while
    (true) {
      socket s=ss.accept ();
      OutputStream Os=s.getoutputstream ();
      Os.write ("Hello, you have received the New Year's Greetings from the server!" N ". GetBytes (" Utf-8 "));
      Os.close ();
      S.close ();}}

  

Client programs

Package my.learn.tcp;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.net.Socket;

Import java.net.UnknownHostException;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.util.Log;

Import Android.widget.EditText;

  public class SimpleClient extends activity {private EditText show; @Override protected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method stub super.oncreate
    (savedinstancestate);
    Setcontentview (R.layout.main);

    Show = (edittext) Findviewbyid (r.id.show);
      try {Socket socket = new Socket ("IP address of your own computer", 30000);
      10 seconds after setting is considered to be timeout socket.setsotimeout (10000);
      BufferedReader br = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));

      String line = Br.readline ();

      Show.settext ("Data from the server:" +line);
      Br.close ();

    Socket.close (); catch (Unknownhostexception e) {//TODO Auto-generaTed Catch Block Log.e ("Unknownhost", "Data from server");
    E.printstacktrace ();
      catch (IOException e) {log.e ("IOException", "Data from server");
    TODO auto-generated Catch block E.printstacktrace ();

 }
  }
}

It should be noted that in the Manifest.xml file, access to the Internet needs to be authorized.

<uses-permission android:name= "Android.permission.INTERNET"/>

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.