what is socket

Socket as an abstraction layer, applications through it to send and receive data, the use of socket applications and other applications in the same network for communication and interaction. In short, socket provides a port for the application to communicate with the outside world and a channel for the communication parties to transmit data.

contrast

Android can communicate with the server in two ways: Http communication and Socket communication.

Differences:

Http communication

  • Request-response mode”
  • When a request is made, a connection channel is established. After the client sends a request to the server, the server can return data to the client

The Socket communication

  • After the two parties establish a connection, data can be directly transmitted. During the connection, information can be actively pushed, instead of the client sending requests to the server every time
  • Low data loss rate, easy to use, easy to transplant

model

The basic Socket communication modes are as follows:

It can be seen from the above model that Socket can be Socket communication based on Tcp protocol or Udp protocol. Today, THE author will talk about Socket communication based on Tcp.

Tcp communication model is as follows:

After understanding the model, the first need to understand the Tcp Socket principle, emphasis to ~

The principle of

The server first declares a ServerSocket object and specifies a port number, and then calls the ServerSocket accept() method to receive data from the client. The Accept () method is blocked when there is no data to receive. (Socketsocket=serversocket.accept())), once received, read the received data through inputStream. The client creates a Socket object and specifies the server IP address and port number (Socket Socket =new Socket(“172.17.30.12”,9999);) OutputStream = socket.getOutputStream(); Finally, the data to be sent is written to outputStream for TCP socket data transmission.

practice

If you understand the principles, you need practice. Chairman MAO once said, “Practice is the only criterion for testing truth.” Code goes ~~~

Client:

package cn.jianke.socket.tcp;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

/** * @className: TcpSocketClient * @classDescription: TCP socket client * @author: leibing * @createTime: 2016/10/06 */
public class TcpSocketClient {
    // Server address
    private String serverIp = "172.17.30.12";
    // The server port number
    private int serverPort = 9999;
    / / socket
    private Socket mSocket = null;
    // Buffer read
    private BufferedReader in = null;
    // Character print stream
    private PrintWriter out = null;
    // TCP socket listening
    private TcpSocketListener mTcpSocketListener;
    / / content
    private String content = "";

    /** * constructor * @author leibing * @createTime 2016/10/06 * @lastmodify 2016/10/06 * @param mTcpSocketListener TCP socket listener * @return */
    public TcpSocketClient(TcpSocketListener mTcpSocketListener){
        this.mTcpSocketListener = mTcpSocketListener;
    }

    /** * constructor * @author leibing * @createTime 2016/10/06 * @lastmodify 2016/10/06 * @param serverIp = server address * @param ServerPort Service port number * @param mTcpSocketListener TCP socket listener * @return */
    public TcpSocketClient(String serverIp, int serverPort , TcpSocketListener mTcpSocketListener){
        this.serverIp  = serverIp;
        this.serverPort = serverPort;
        this.mTcpSocketListener = mTcpSocketListener;
    }

    /** * Start TCP socket connection * @author leibing * @createTime 2016/10/06 * @lastmodify 2016/10/06 * @param * @return */
    public void startTcpSocketConnect(){
        // Start a thread to start the TCP socket
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    mSocket = new Socket(serverIp, serverPort);
                    in = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
                    out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
                            mSocket.getOutputStream())), true);
                    while (true) {
                        if (mSocket.isConnected()) {
                            if(! mSocket.isInputShutdown()) {if ((content = in.readLine()) ! =null) {
                                    content += "\n";
                                    if(mTcpSocketListener ! =null)
                                        mTcpSocketListener.callBackContent(content);
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /** * Send message via TCP socket * @author leibing * @createTime 2016/10/06 * @lastmodify 2016/10/06 * @param * @return */
    public void sendMessageByTcpSocket(String msg){
        if(mSocket ! =null && mSocket.isConnected()){
            if(! mSocket.isOutputShutdown() && out ! =null){
                out.println(msg);
                if(mTcpSocketListener ! =null) mTcpSocketListener.clearInputContent(); }}}/** * @interfacename: * @interfaceDescription: TCP socket listener * @author: leibing * @createTime: 2016/10/06 */
    public interface TcpSocketListener{
        // Call back the content
        void callBackContent(String content);
        // Clear the input field
        voidclearInputContent(); }}Copy the code

Encapsulates a TcpSocket client class, writes the constructor, sets the server IP address, port number, and listener (used to call back data received from the Socket server), writes the TCP Socket connection method, where BufferedReader in is used to receive server data. PrintWriter out is used to send data to the server.

package cn.jianke.socket.module;

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import cn.jianke.socket.R;
import cn.jianke.socket.tcp.TcpSocketClient;

/** * @className:MainActivity * @classDescription: TCP socket client page * @author: leibing * @createTime: 2016/10/06 */
public class MainActivity extends AppCompatActivity {
    // Server address
    private final static String serverIp = "172.17.30.12";
    // Service port number
    private final static int serverPort = 9999;
    / / control
    private TextView showTv;
    private EditText contentEdt;
    private Button sendBtn;
    // TCP socket client
    private TcpSocketClient mTcpSocketClient;
    // Custom Handler to update Ui
    private Handler mHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // findView
        showTv = (TextView) findViewById(R.id.tv_show);
        contentEdt = (EditText) findViewById(R.id.edt_content);
        // Initialize the TCP socket client
        mTcpSocketClient = new TcpSocketClient(serverIp, serverPort,
                new TcpSocketClient.TcpSocketListener() {
            @Override
            public void callBackContent(final String content) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if(showTv ! =null) showTv.setText(showTv.getText().toString() + content); }}); } @Override publicvoid clearInputContent() {
                        if(contentEdt ! =null)
                            contentEdt.setText(""); }});// Start a TCP socket connection
        mTcpSocketClient.startTcpSocketConnect();
        // onClick
        findViewById(R.id.btn_send).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Stringmsg = contentEdt.getText().toString().trim(); mTcpSocketClient.sendMessageByTcpSocket(msg); }}); } @Override protectedvoid onDestroy() {
        // Disconnect the TCP connection
        if(mTcpSocketClient ! =null)
            mTcpSocketClient.sendMessageByTcpSocket("exit");
        super.onDestroy(); }}Copy the code

On the page, start the TcpSocketClient class (set the server IP address, port, and listener) and start the TCP socket connection.

Server:

package cn.jianke.socket.tcp;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/** * @className: TcpSocketServer * @classDescription: TCP socket server * @author: leibing * @createTime: 2016/10/06 */
public class TcpSocketServer {
    / / the port number
    private final static int serverPort = 9999;
    // TCP socket list
    private List<Socket> mList = new ArrayList<Socket>();
    // Socket service
    private ServerSocket server = null;
    / / thread pool
    private ExecutorService mExecutorService = null;

    /** * @author leibing * @createTime 2016/10/06 * @lastmodify 2016/10/06 * @param args * @return */
    public static void main(String[] args) {
        // Start the TCP socket service
        new TcpSocketServer();
    }

    /** * Start TCP socket service * @author leibing * @createTime 2016/10/06 * @lastmodify 2016/10/06 * @param * @return */
    public TcpSocketServer() {
        try {
            server = new ServerSocket(serverPort);
            System.out.print("server start ...");
            Socket client = null;
            //create a thread pool
            mExecutorService = Executors.newCachedThreadPool();
            while(true) {
                client = server.accept();
                mList.add(client);
                //start a new thread to handle the connection
                mExecutorService.execute(newTcpSocketService(client)); }}catch(Exception e) { e.printStackTrace(); }}/** * @className: TcpSocketService * @classDescription: TCP socket service * @author: leibing * @createTime: 2016/10/06 */
    class TcpSocketService implements Runnable {
            / / socket
            private Socket socket;
            // Buffer read
            private BufferedReader in = null;
            / / message
            private String msg = "";

            /** * constructor * @author leibing * @createTime 2016/10/06 * @lastmodify 2016/10/06 * @param socket * @return */
            public TcpSocketService(Socket socket) {
                this.socket = socket;
                try {
                    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    msg = "tips: user" +this.socket.getInetAddress() + " come";  
                    this.sendmsg();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    while(true) {
                        if((msg = in.readLine())! =null) {
                            if(msg.equals("exit")) {
                                mList.remove(socket);
                                in.close();
                                msg = "tips: user" +this.socket.getInetAddress() + " exit";
                                socket.close();
                                this.sendmsg();
                                break;
                            } else {
                                msg = socket.getInetAddress() + ":" + msg;
                                this.sendmsg(); }}}}catch(Exception e) { e.printStackTrace(); }}/** * @author leibing * @createTime 2016/10/06 * @lastmodify 2016/10/06 * @param * @return */
        public void sendmsg() {
               System.out.println(msg);
               int num =mList.size();
               for (int index = 0; index < num; index ++) {
                   Socket mSocket = mList.get(index);
                   PrintWriter pout = null;
                   try {
                       pout = new PrintWriter(new BufferedWriter(
                               new OutputStreamWriter(mSocket.getOutputStream())),true);
                       pout.println(msg);
                   }catch (IOException e) {
                       e.printStackTrace();
                   }
               }
           }
        }    
}Copy the code

Initialize the ServerSocket specified port to put the TCP socket service into the thread pool to interact with the client. BufferedReader in is used to receive data from the client. PrintWriter pout is used to send data to the client.

rendering

Server:

server start ... tips: user/172.1730.15. come
/172.1730.15.: enough /172.1730.15.: not enough /172.1730.15.Hagen /172.1730.15.: In the picture /172.1730.15.: Normot /172.1730.15.This is a socket /172.1730.15.:hgdhCopy the code

Client:

Demo address: Socket

About the author

  • QQ:872721111
  • Email:[email protected]
  • Github:leibing@github
  • Jane: leibing @ jianshu
  • The Denver nuggets: leibing @ juejin