preface

  • SocketThe use of theAndroidVery important in network programming
  • Today I’m going to take you through itSocketAnd how to use it



directory


1. Network basics

1.1 Computer network layering

Computer network is divided into five layers: physical layer, data link layer, network layer, transport layer, application layer

Among them:

  • Network layer: hosts that locate destination IP addresses based on IP addresses
  • Transport layer: data is transmitted to the destination process of the destination host through ports to realize the communication between processes

1.2 PORT Number (PORT)

The port number is specified as 16 bits, which allows an IP host to have 2 to the power of 16 to 65535 different ports. Among them:

  • 0 to 1023: port number assigned to the system


    We can’t mess with it

  • 1024 to 49151: registration port number used by third-party applications

    But you have to register with IANA (Internet Digital Distribution Agency),

  • 49152 to 65535: indicates the temporary port number. This port is reserved for client processes to use temporarily. After one process is used, other processes can use it.

When Socket is used, the port number ranges from 1024 to 65535

1.3 C/S structure

  • Definition: client/server architecture, software system architecture
  • Function: Make full use of the advantages of the hardware environment at both ends, allocate tasks reasonably to the Client and Server to achieve, reducing the communication cost of the system.


    Socket uses this structure to establish connections, one Socket client, one Socket server.






1.4 the TCP protocol

  • Transmission Control Protocol is a transport layer communication Protocol


    Tcp-based application layer protocols include FTP, Telnet, SMTP, HTTP, POP3, and DNS.

  • Features: connection-oriented, byte stream oriented, full duplex communication, reliable

    • Connection-oriented: To use TCP to transfer data, a TCP connection must be established and released after transmission, just as a phone call must be made and a connection must be established.

    • Full-duplex communication: Once a TCP connection is established, the communication parties can send data at any time.

    • Reliable: Refers to data transmitted over a TCP connection that is error-free, not lost, not duplicated, and arrives in sequence.

    • Byte stream: stream, a sequence of characters flowing into or out of a process. In simple terms, although sometimes to transmit the data flow is too large, the TCP packet length is limited, can’t finish a transfer, to put it into several blocks of data, but because of reliability assurance, the receiver can receive data blocks in sequence and then reconstitute block the flow of data before, so the TCP looks like direct transmission byte stream to each other, face to the byte stream.

  • A three-way handshake is required to establish A TCP connection. This handshake is required if user A wants to connect user B

    • First handshake: Establish a connection. The client sends a connection request packet segment and sets the SYN position to 1 and Sequence Number to X. The client then enters the SYN_SEND state and waits for confirmation from the server. So A sends A message to B
    • Second handshake: The server receives a SYN packet from the client and needs to confirm the SYN packet. After receiving the connection information, USER B sends A confirmation message to user A
    • Third handshake: The client receives a SYN+ACK packet from the server and sends an ACK packet to the server. After receiving the confirmation message, user A sends the confirmation message to user B

    At this point, A tells itself that the upper-layer connection is established. B sends a message to the upper layer to establish a connection.

This completes the TCP three-way handshake = a TCP connection is established = you can start sending data

  1. If you do not receive any reply from the other person during the three handshakes, resend it.
  2. After the last confirmation packet is sent, both the client and server enter the ESTABLISHED state.

Why does TCP require a three-way handshake to establish a connection?

A: Prevents the server from wasting resources by waiting for client requests after receiving invalid connection request packets

  • Invalid connection request segment Is generated in this case: The first connection request segment sent by the Client is not lost, but is detained on a network node for a long time. As a result, it is delayed until a certain time after the connection is released.
  • This is an invalid message segment. However, after the Server receives the invalid connection request packet segment, it mistakenly thinks it is a new connection request sent by the Client.
  • Then the Client sends a confirmation message to agree to establish a connection.
  • Assume that the “three-way handshake” is not used: as soon as the Server sends an acknowledgement, a new connection is established.
  • The Client is not sending data to the Server because it is not making a connection request.
  • However, the Server assumes that the new transport connection has been established and waits for data from the Client. > < span style = “max-width: 100%; clear: both; min-height: 1em;

This can be prevented by using the three-way handshake:

  • The Client does not issue an acknowledgement to the Server’s acknowledgement
  • Since the Server receives no acknowledgement, it knows that the Client has not requested a connection
  • Therefore, the Server does not wait for the Client to send data, and resources are not wasted

  • TCP release connection TCP release requires four waves. Now assume that user A releases the connection :(after data transmission ends, both parties can release the connection.)

    • First wave: A sends release message to B; (After sending, A->B sends data the path is broken.)
    • Second wave: after receiving A’s release message, B replies with A confirmation message: I agree to your release connection request

    • Third wave: B sends A “request to release the connection” message to A

    • Fourth wave: AFTER receiving the message sent by B, A sends A confirmation release message to B: I agree to your request to release the connection

      B officially closes the connection after receiving the confirmation message. If A still does not receive A reply after waiting for 2MSL, it proves that end B is normally closed, so A closes the connection

Why does TCP release a connection with four waves?

In order to ensure that both parties can notify each other that they “need to release the connection”, neither party can receive or send messages to the other party after releasing the connection

  • To be clear: TCP is in full-duplex mode, which means that both sending and receiving can be done in both directions
  • The definition of releasing a connection is that neither party can receive or send a message to the other
  • If host 1 sends a FIN packet, no data is to be sent or all data has been sent.


    However, host 1 can still accept data from host 2 at this point.

  • When host 2 returns an ACK message confirming the release of the connection, it indicates that it knows that host 1 has no data to send, but host 2 can send data to host 1
  • If host 2 also sends a FIN packet, that is, host 1 has no data to send either. In this case, hosts 1 and 2 cannot communicate with each other. Host 1 cannot send data to host 2, and host 2 cannot send data to host 1
1.5 the UDP protocol
  • Definition: The User Datagram Protocol is a transport layer communication Protocol.

    Udp-based application layer protocols include TFTP, SNMP, and DNS.

  • Features: connectionless, unreliable, message-oriented, no congestion control

    • Connectionless: and TCP to establish a connection, UDP transmission data does not need to establish a connection, like writing a letter, in the envelope to write the name of the recipient, address can be sent to the post office, as can not be sent, will depend on the post office’s ability to send a letter and the difficulty of the process.

    • Unreliable: Because UDP packets are sent out without care, whether it will arrive or not, packet loss is likely to occur, causing errors in the transmission of data.

    • Packet oriented: A data packet is equivalent to a data packet. UDP sends the same data packet that the application layer sends to UDP. UDP does not split the data packet like TCP.

    • No congestion control: congestion, refers to the group arrived in one part of the communication subnet number too much, making it part of the network to deal with, so that caused the phenomenon of this part and the whole network performance degradation, serious when even lead to network communications business ground to a halt, namely a deadlock phenomenon, like a traffic jam. After a TCP connection is established, if the data sent cannot reach the destination due to the quality of the channel, it will be continuously retransmitted, which may lead to more and more congestion. Therefore, a complex principle is required to control congestion. UDP does not have this worry, sent to no matter.
  • Application Scenarios Many real-time applications (such as IP telephony, real-time video conferencing, and some online multiplayer games) require the source host to send data at a fixed rate and allow the loss of some data in case of network congestion. However, UDP is suitable for this requirement. So there’s only technology that doesn’t fit, and there’s no technology that really doesn’t work.

1.6 the HTTP protocol

See another article I wrote for more details everything you need to know about HTTP is here!


2. The Socket definition

  • A socket is a programming call interface (API) that encapsulates the TCP/IP protocol

    1. throughSocketBefore we can pass it on the Android platformTCP/IPProtocol development
    2. SocketNot a protocol, but a programming call interface (API), which is the transport layer (mainly dealing with how data is transferred over the network)
  • 2. To come in pairs or pairs of sockets:

Socket ={(IP address 1:PORT number), (IP address 2:PORT number)}Copy the code

Principle 3.

There are two types of sockets:

  • Flow socket (streamsocket) :TCPProtocol, adoptedstreamProvides reliable byte stream service
  • Datagram socket (datagramsocket) :UDPProtocol, adoptedThe data packetProvides data packaging and sending service

The specific schematic diagram is as follows:

4. Compare sockets with Http

  • SocketIt’s part of the transport layer becauseTCP / IPProtocols belong to the transport layer,How does the data move across the network
  • HTTPProtocols belong to the application layer.The problem is how to package the data

Because the two do not belong to the same level, so there is no comparison. Over time, however, the following layers of usage have been encapsulated in the default Http protocol, hence the contrast between Socket and Http:

  • Http: adopts request-response mode.

    1. That is, after the network connection is established, the server can return data to the client only after the client sends a request to the server.
    2. The client communicates only when it needs to
  • Socket: The server actively sends data

    1. After the network connection is established, the server can proactively send messages to the client without the client sending requests to the server
    2. It can be interpreted as: the server communicates only when necessary

5. Procedure

  • SocketCan be based onTCPorUDPAgreement,But TCP is more commonly used
  • So the following uses steps & examplesSocketWill be based onTCPagreement
// Step 1: create a client/server connection // Create a Socket object & specify the server IP and port number Socket Socket = new Socket("192.168.1.32", 1989); // Check whether the client and server are successfully connected socket.isconnected ()); // Step 2: client-server communication // Communication includes: client receives data from server & sends data to server <-- Operation 1: receives data from server --> // Step 1: InputStream InputStream is = socket.getinputstream () // step 2: create an InputStream reader and pass in an InputStream reader. InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); // Step 3: receive data from the server through the input stream reader object br.readline (); <-- operation 2: send data to server --> // Step 1: Get OutputStream object from Socket OutputStream = socket.getOutputStream(); // Step 2: Write the data to be sent to outputStream.write ((" Carson_Ho"+"\n").getBytes(" utF-8 ")); // Step 3: Send data to outputstream.flush () on the server; // Step 3: Disconnect the client and server from os.close(); OutputStream br.close(); OutputStream br.close(); OutputStream br.close(); // Disconnect the server from the client, that is, close the input stream reader object BufferedReader socket.close(); // Finally close the entire Socket connectionCopy the code

6. Concrete examples

  • The instanceDemoThe code includes: client & server
  • This article focuses on the client side, and the server is shown in the simplest form

6.1 Client Implementation

Step 1: Add network permissions

<uses-permission android:name="android.permission.INTERNET" />Copy the code

Step 2: Set the main layout screen

Includes buttons to create Socket connections and client-server communication

    <Button
        android:id="@+id/connect"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="connect" />

    <Button
        android:id="@+id/disconnect"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="disconnect" />

    <TextView
        android:id="@+id/receive_message"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/Receive"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Receive from message" />

    <EditText
        android:id="@+id/edit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/send"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="send"/>
Copy the code

Step 3: Create Socket connections and client-server communication

Please refer to the notes for details

MainActivity.java

package scut.carson_ho.socket_carson; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; Public class MainActivity extends AppCompatActivity {/** * main variable */ // main thread Handler // used to display messages obtained from the server private Handler mMainHandler; // Socket variable private Socket Socket; Private ExecutorService mThreadPool; // ExecutorService mThreadPool; /** * Receive server message variable */ / InputStream is; // InputStreamReader isr; BufferedReader br ; // Receive the message sent by the server String response; /** * Send message to server variable */ / OutputStream OutputStream; Private Button btnConnect, btnDisconnect, btnSend; private Button btnConnect, btnDisconnect, btnSend; Private TextView Receive,receive_message; Private EditText mEdit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); BtnConnect = (Button) findViewById(r.i.C.onnect); btnDisconnect = (Button) findViewById(R.id.disconnect); btnSend = (Button) findViewById(R.id.send); mEdit = (EditText) findViewById(R.id.edit); receive_message = (TextView) findViewById(R.id.receive_message); Receive = (Button) findViewById(R.id.Receive); / / initialize the thread pool mThreadPool = Executors. NewCachedThreadPool (); MMainHandler = new Handler() {@override public void handleMessage(Message MSG) {switch (msg.what) { case 0: receive_message.setText(response); break; }}}; / * * * create client & server connection. * / btnConnect setOnClickListener (new View. An OnClickListener () {@ Override public void onClick (View v) Mthreadpool.execute (new Runnable() {@override public void run() {try {// Create Socket object & Socket = new socket ("192.168.1.172", 8989); System.out.println(socket.isconnected ()); } catch (IOException e) { e.printStackTrace(); }}}); }}); Process server message / * * * * / Receive setOnClickListener (new View. An OnClickListener () {@ Override public void onClick (View v) {/ / Mthreadpool.execute (new Runnable() {@override public void run() {try {// Step 1: InputStream is = socket.getinputStream (); Isr = new InputStreamReader(is); isr = new InputStreamReader(is); br = new BufferedReader(isr); Response = br.readline (); // Step 3: Receive data from the server via the input stream reader. // Step 4: notify the main thread to display the received messages to the interface Message MSG = message.obtain (); msg.what = 0; mMainHandler.sendMessage(msg); } catch (IOException e) { e.printStackTrace(); }}}); }}); / * * * send a message to the server. * / btnSend setOnClickListener (new View. An OnClickListener () {@ Override public void onClick (View v) {/ / Mthreadpool.execute (new Runnable() {@override public void run() {try {// Step 1: OutputStream = socket.getOutputStream(); // step 2: write the data to be sent to the outputStream object outputstream.write ((medit.gettext ().tostring ()+"\n").getbytes ("utf-8")); // Step 3: Send data to outputstream.flush () on the server; } catch (IOException e) { e.printStackTrace(); }}}); }}); / * * * disconnect the client & server. * / btnDisconnect setOnClickListener (new View. An OnClickListener () {@ Override public void onClick (View V) {try {// Disconnect the client from the server, that is, close OutputStream outputstream.close (); BufferedReader br.close(); // Disconnect the server from the client, that is, close the input stream reader object. // Finally close the entire Socket connection socket.close(); System.out.println(socket.isconnected ()); // Check whether the client and server are disconnected. } catch (IOException e) { e.printStackTrace(); }}}); }}Copy the code

6.2 Server Implementation

  • Since this article focuses on the client side, the server is only intended to accompany the client presentation;
  • In order to simplify the server usage, this is used hereMinaThe framework
  1. The server code is available ateclipsePlatform to run
  2. Follow my steps step by step and you can run mindless

Step 1: ImportMinapackage

Please go directly to Baidu web disk: Download link (password: Q73E)

Step 2: Create the server thread testhandler.java

package mina; Public class TestHandler extends IoHandlerAdapter {@override public void exceptionCaught(IoSession session, Throwable cause) throws Exception { System.out.println("exceptionCaught: " + cause); } @Override public void messageReceived(IoSession session, Object message) throws Exception { System.out.println("recieve : " + (String) message); session.write("hello I am server"); } @Override public void messageSent(IoSession session, Object message) throws Exception { } @Override public void sessionClosed(IoSession session) throws Exception { System.out.println("sessionClosed"); } @Override public void sessionOpened(IoSession session) throws Exception { System.out.println("sessionOpen"); } @Override public void sessionIdle(IoSession session, IdleStatus status) throws Exception { } }Copy the code

Step 3: Create the server main code testhandler.java

package mina; import java.io.IOException; import java.net.InetSocketAddress; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.textline.TextLineCodecFactory; import org.apache.mina.transport.socket.nio.NioSocketAcceptor; public class TestServer { public static void main(String[] args) { NioSocketAcceptor acceptor = null; try { acceptor = new NioSocketAcceptor(); acceptor.setHandler(new TestHandler()); acceptor.getFilterChain().addLast("mFilter", new ProtocolCodecFilter(new TextLineCodecFactory())); acceptor.setReuseAddress(true); acceptor.bind(new InetSocketAddress(8989)); } catch (Exception e) { e.printStackTrace(); }}}Copy the code

At this point, the client and server code are completed.


6.3 Test Results

  • Click on theConnectButton: The connection is successful

  • Enter the message to send and clickSendButton to send

  • The server receives the message sent by the client. Procedure

  • Click on theReceive From MessageButton that the client reads the message returned by the server

  • Click on theDisConnectButton to disconnect client from server


6.4 Source Code Address

Github address of Carson_Ho: Socket instance


7. To summarize

  • I believe you are very familiar with the use of sockets
  • So I’m going to continue with thisAndroidNetwork programming to explain, interested can continue to pay attention toCarson_Ho android Development Notes

Please give a thumbs-up or comment! Because your encouragement is the biggest power that I write!