Android TCP Socket communication client/server Demo (with APP source code)

This article mainly explains the implementation of Android TCP Socket communication client (Client) and server (Server) Demo (with source code), pay attention to the readLine() method of BufferedReader [((line = br.readLine()) != null )] The blocking problem, and the conversion processing of the project data of the docking hardware in the hexadecimal &&byte&&int.

Tai Hang

Recently, there was a project that needed to use TCP Socket communication and encountered a big pit, so I made this demo.
When reading the socket input stream, many codes will write this way, and there is generally no problem, but the readLine() method will block when it cannot read the line feed and carriage return!
String line = null;
while ((line = br.readLine()) != null) {
}
readLine() is a blocking function, you can click to view the source code, only when you encounter line feed or carriage return ('\n' ,'\r' corresponding to hexadecimal is 0D 0A) will return, and some modules return data to you without these two terminators, so it causes blocking and the program cannot go on. In this case, if the module side is willing to modify and add a terminator, it will be no problem. If the module is inconvenient to change, then this method cannot be used, and the writing method must be changed.

Debugging tools

For real-time debugging, we can use some PC-side tools, such as TCP debugging assistants and TCP testing tools. There are a lot of users, and the operation is also foolish. Fill in the IP and port and then establish or connect.
Insert picture description here
Android TCP Socket communication client/server Demo (with APP source code)

Demo demonstration and implementation

Stop talking nonsense, go directly to today's topic, let's take a look at how to use TCP/IP protocol on Android to communicate with Server using Socket!
Insert picture description here

1. Permission

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

Second, the server implementation, in simple terms, it takes 3 steps

1. Create a ServerSocket, monitor the port, and wait for the client Socket to connect.
2. Get the message from the client from the Socket.
3. Send a message to the client through the Socket.

The core code is as follows

class ServerSocketThread extends Thread {

    @Override
    public void run() {
        try {  
           // 创建ServerSocket  
           ServerSocket serverSocket = new ServerSocket(9999);  
           System.out.println("--开启服务器,监听端口 9999--");  

           // 监听端口,等待客户端连接  
           while (true) {  
               System.out.println("--等待客户端连接--");  
               Socket socket = serverSocket.accept(); //等待客户端连接  
               System.out.println("得到客户端连接:" + socket);  

               startReader(socket);  
           }  

       } catch (IOException e) {  
           e.printStackTrace();  
       } 
    }
}

   /**  
    * 从参数的Socket里获取消息 
    */  
   private static void startReader(final Socket mSocket) {  
       new Thread(){  
           @Override  
           public void run() {  
               try {  
                   // 获取读取流  
                   BufferedReader in = new BufferedReader(new InputStreamReader(mSocket.getInputStream(),"utf-8"))
                   String line="";
                   while ((line = in.readLine()) != null) {// 读取数据  
                       System.out.println("*等待客户端输入*");  
                       System.out.println("获取到客户端的信息:" + line);
                    }
               } catch (IOException e) {  
                   e.printStackTrace();  
               }  
           }  
       }.start();  
   } 

 //通过socket来给客户端发送消息
 private void serverSendMessage(String mServerSendMessage) {
     new Thread() {
         @Override
         public void run() {
             PrintWriter out;
             try {
                 out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream())), true);
                 out.println(mServerSendMessage);
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
     }.start();
  }

Three, client-side implementation, similar to the server-side process

1. Establish a Socket connection with the server
2. Obtain input and output streams
3. Receive/send messages

//与服务器建立连接
Socket mClientSocket = new Socket(mClientIp, mClientPort);

//从socket获取输入输出流
BufferedReader mClientIn = new BufferedReader(new InputStreamReader(mClientSocket.getInputStream()));
PrintWriter mClientOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(mClientSocket.getOutputStream())), true);

//监听服务端下发的消息
String clientReceiverMessage;
if ((clientReceiverMessage = mClientIn.readLine()) != null) {
    if (mOnConnectListener != null) {
        mOnConnectListener.onMessage(clientReceiverMessage);
    }
} 

//给服务端发消息
mClientOut.println(mClientSendMessage);

Code package Listener interface

In the actual development process, we generally encapsulate the Socket, and then set up the Listener interface externally, handle business logic in other modules, and some need to handle multiple socket connections and communications.

Server-side code implementation example

public class TcpServer {

    private static final String TAG = "TcpServer";

    private static TcpServer mTcpServer = new TcpServer();
    private OnListener mOnListener;
    private ServerSocketThread mServerSocketThread;

    public static TcpServer getInstance() {
        return mTcpServer;
    }

    public void setOnListener(OnListener onListener) {
        mOnListener = onListener;
    }

    public interface OnListener {
        void onStart();

        void onNewClient(String serverIp, String clientIp, int count);

        void onError(Throwable e, String message);

        void onMessage(String ip, String message);

        void onAutoReplyMessage(String ip, String message);

        void onClientDisConnect(String ip);

        void onConnectTimeOut(String ip);
    }

    public void setPort(int port) {
        mServerPort = port;
    }

    ………………………………
    ………………………………
    ………………………………
}

Hexadecimal sending and receiving processing

The communication protocol of the docking hardware project may use hexadecimal, so the data should be converted in the string \byte\int hexadecimal, but the essence of the communication part is the same, the code is as follows

  //十六进制 发送
  try {
      //byte[] msg = {(byte) 0xaa,(byte) 0xbb,(byte) 0x0d,(byte) 0x0a};
      byte[] msg = IntByteStringHexUtil.hexStrToByteArray("AABB0D0A");
      OutputStream socketWriter = socket.getOutputStream();

      socketWriter.write(msg);
  } catch (IOException e) {
      e.printStackTrace();
  }

  //十六进制 接收
  InputStream socketReader = socket.getInputStream();
  byte buf[] = new byte[1024];
  int len = socketReader.read(buf);

  byte data[] = new byte[len];
  System.arraycopy(buf, 0, data, 0, len);

  logClient(len+","+IntByteStringHexUtil.byteArrayToHexStr(data));

Demo source download address

The source code is also placed on CSDN, you can learn from it if you need it

===> Android TCP Socket communication example Demo source code Apk download

Guess you like

Origin blog.51cto.com/12521475/2658251