Android client and local server socket communication

Source: Internet
Author: User

Android client and local server socket communication

Socket server run result diagram??

I. Client and server-side selection:
    • Client is our mobile phone, about the server side, as long as the installation of the JDK, naturally have the function of communication, we only need to write in eclipse or myeclipse the server-side code in the article, run up, with the Accept () method to start the server side, waiting for the client connection, The server side is in a blocked state when it is not connected.
Two. Client Considerations
  • Andriod Client Add Network access rights
    <uses-permission android:name="android.permission.INTERNET" />

  • Operations on the socket are placed within a non-UI thread

  • To use the correct IP address and port number the range of port numbers is 0~65535,1024 the ports are assigned to some services by the system, and the CMD window executes netstat -ano commands to see the usage of all ports

  • The real machine for debugging (1, connect on the phone, mobile phone open adb. Steps: Settings > Applications > Development > select USB debugging; USB option is not visible, specific Baidu), specify the IP address of the server, this address is the LAN address, if you are using WiFi, then the WiFi IP of the PC. The second of the connections is an example .
    Three. Socket communication
  • Using the IP address + port number uniquely identifies a process in the network that uniquely identifies the processes in the network, and they can use the socket for communication.

  • The socket is an abstraction layer between the application layer and the transport layer, which abstracts the complex operation of TCP/IP layer into a few simple interface supply layer calls to implement the process of communication in the network.

  • The socket is an implementation of "open-read/write-off" mode (only the data that is placed in the stream can be read), as an example of a socket that uses TCP protocol communication, the interaction process is probably the same

  • There are two main ways to operate a socket: connection-oriented and non-connected, that is, TCP and UDP.
    A connection-oriented socket operation is like a phone, the socket must connect to the destination socket before sending the data, and once the connection is established, the socket can be opened, read-write, and closed using a stream interface. Also, all data sent will be received in the same order on the other end.

  • A disconnected socket operation is like a mail delivery, and each datagram is a separate unit that contains all the information about the delivery (the destination address and the content to be sent). The socket in this mode does not need to connect to the destination socket, it simply throws out the datagram.
    Four. The difference between a TCP connection and an HTTP connection and a socket connection
  • The difference between a TCP connection and an HTTP connection

HTTP is TCP-based , and the first step when a client sends an HTTP request to the server is to establish a TCP connection to the server.

    • The difference between a TCP connection and a socket connection:

The socket layer is just an abstraction interface layer on the TCP/UDP Transport layer, the TCP protocol-based socket connection also needs to be connected through three handshake, is reliable; UDP protocol-based socket connection does not need to establish a connection process, but the other side can receive will send the past, is unreliable, most instant messaging im are the latter.

    • The difference between an HTTP connection and a socket connection

HTTP is a short connection , and the Socket (based on TCP protocol) is a long connection . Although HTTP1.1 begins to support persistent connections, it is still not guaranteed to always connect. In the case of a socket connection, the connection state is maintained once the TCP three handshake is established, unless one is actively disconnected.

The HTTP connection server cannot proactively send messages. Decide which scenarios are appropriate for each application. HTTP takes a "request-response" mechanism that must satisfy the client to send a message before the server replies back. Socket connection similar to the peer2peer relationship, one party may at any time shout to the other party.

    • When to use HTTP, when to use the socket

In the case of http: The two sides do not need to stay connected online, such as the acquisition of client resources, file upload and so on.

With sockets: Most instant Messaging Applications (QQ,), chat rooms, Apple APNs, etc.

Five. Socket code

Client code

public class Mainactivity extends Appcompatactivity {//IP address and port number public static String ip_address = "192.168.1.106";p ublic s tatic int PORT = 2346;//three controls edittext text = null; Button connect = null; TextView info = Null;//handlerhandler handler = null; Socket Soc = null;dataoutputstream dos = null;datainputstream dis = null; String messagerecv = null, @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancest    ATE);    Setcontentview (R.layout.activity_main);    Text = (EditText) Findviewbyid (R.id.edittext);    Connect = (Button) Findviewbyid (r.id.buttonconnection);    info = (TextView) Findviewbyid (r.id.info); Connect.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {n        EW Connectionthread (Text.gettext (). toString ()). Start ();    }    }); Handler = new Handler () {@Override public void Handlemessage (Message msg) {super.handlemessage (            msg); Bundle B = Msg.getData ();  Gets the bundle object in the message, String str = b.getstring ("Data");        Gets the value of the string with the key of data info.append (str); }    };    }//Create a new child thread to implement socket communication class Connectionthread extends thread {String message = NULL;    Public Connectionthread (String msg) {message = MSG; @Override public void Run () {if (Soc = = null) {try {//log.d ("socket", "New sock                ET ");                Soc = new Socket (ip_address, PORT);                Gets the input and output stream of the socket dis = new DataInputStream (Soc.getinputstream ());            DOS = new DataOutputStream (Soc.getoutputstream ());            } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();            }} try {DOS.WRITEUTF (message);            Dos.flush ();            MESSAGERECV = Dis.readutf ();//If no data is received, the message msg = new Message () is blocked;            Bundle B = new bundle ();B.putstring ("Data", MESSAGERECV);            Msg.setdata (b);        Handler.sendmessage (msg);        } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); }    }}}

'
Server-side code

public class Server {ServerSocket ServerSocket = null;public final int port = 2346;public Server () {//Output server IP address            try {inetaddress addr = Inetaddress.getlocalhost ();            SYSTEM.OUT.PRINTLN ("Local Host:" +ADDR);            ServerSocket = new ServerSocket (port);        System.out.println ("0k");        } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();        }}public void StartService () {try {socket socket = NULL;        System.out.println ("Waiting ..."); Wait for the connection, create a new thread for each connection, and then (true) {socket = serversocket.accept ();//wait for a client connection before the connection is            The System.out.println is blocked ("Connect to" +socket.getinetaddress () + ":" +socket.getlocalport ());        New Connectthread (socket). Start ();        }} catch (IOException e) {//TODO auto-generated catch block System.out.println ("IOException");    E.printstacktrace (); }}//sending information to the client CLASS Connectthread extends thread{socket socket = NULL;        Public connectthread (socket socket) {super ();    This.socket = socket; } @Override public void Run () {try {datainputstream dis = new DataInputStream (socket.getinputstre            AM ());            DataOutputStream dos = new DataOutputStream (Socket.getoutputstream ());                while (true) {String msgrecv = Dis.readutf ();                System.out.println ("Msg from client:" +MSGRECV);                Dos.writeutf ("Received:" +MSGRECV);            Dos.flush ();        }} catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); }}}public static void Main (string[] args) {//TODO auto-generated method Stub new Server (). StartService ();}}
The logic of the Code

Client:

    1. Initializes the control, binds the listener, and writes the button's event-handling code.

    2. The child thread is opened in the event-handling code, and the server is accessed through sockt in the child thread.
    3. Using the asynchronous message processing mechanism, the message object passes the child thread's data back to the handle's processing method to update the UI.

Service side

    1. The ServerSocket object listens to wait and uses the loop to turn on the sub-threading process to send messages back to the client when there is client access. (both simulator and phone are accessed via LAN)
      The last crap.
    1. The computer must have the theory to guide the practice, otherwise only like a chicken everywhere, my computer network knowledge is really long story.

    2. The official website of the major languages is a good thing. A wealth of information and tutorials are simply intoxicating. Although it is not as easy to understand as Internet fiction, it is not bad to be fascinating.
    3. Not too many things, with Google plug-ins and other tools list, first solve the main, usually have ideas can also be recorded.

    4. Use blogs to organize your knowledge and form a system. It's better to read it than to do it again.

PS. Integrates a lot of local knowledge points, official website, bloggers, do not record the original address.

2018-05-13 22:15:53 Sunday

Android client and local server 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.