Android entry notes-network communication-Socket

Source: Internet
Author: User

Android entry notes-network communication-Socket

Let's take a look at the socket in the Communication Mode in android. The last two times we used HttpURLConnection and HttpClient to implement communication. Both of them are using the HTTP protocol, which is called a Socket. The protocols used are TCP and UDP, the difference between TCP and UDP is that TCP is reliable and stable and comes with advantages such as fault tolerance Processing, so the efficiency is lower. Then UDP is not so stable. When UDP is used to send data, each time the data is sent, the socket only sends the data, regardless of whether the other party receives the data after sending and whether the order is correct, therefore, UDP is called unstable transmission, but its efficiency is very high, because it is very simple to do.

Today, we learned that socket uses the tcp protocol. In android, socket is actually used in java. You can see the application package


Let's complete a small LAN chat program, including a server, android app as a client, after a mobile phone sends information, the server will forward it to other mobile phones, which is very simple. There are many codes, which are attached later. Let's first look at how to use socket.



Client Socket steps:

(1) Socket mSocket = new Socket (SERVER_IP, SERVER_PORT); // the two parameters are the Server IP address and the server listening port respectively.

(2) BufferedReader mBufferReader = new BufferedReader (new InputStreamReader (mSocket. getInputStream (); // use socket. getInputStream () can get the input stream and obtain the data sent by the server from the socket. In order to read one row in one row, we can convert it to BufferReader. You can use BufferReader. readLine () to retrieve the data waiting for a row on the socket.

(3) PrintWriter mPrintWriter = new PrintWriter (mSocket. getOutputStream (), true); // use socket. getOutputStream () can get the input stream and send data to the server through socket. here we need to set up the PrintWriter standard interface to use mPrintWriter. println ("...), send data directly.

(4) disconnect after use.

Let's take a look at the instance:


mSocket = new Socket(SERVER_IP, SERVER_POART);mBufferReader = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));mPrintWriter = new PrintWriter(mSocket.getOutputStream(), true);
If no Exception is reported, the connection to the server is successful. In this case, you can use mBufferReader and mPrintWrinter to send and receive data.


Read data:


                while (true) {                    if (null != (mStrMsg = mBufferReader.readLine())) {                        mStrMsg += ;                        if(mStrMsg.trim().equals(exit)){                            mHandler.sendMessage(mHandler.obtainMessage(2));                            return ;                        }                        mHandler.sendMessage(mHandler.obtainMessage(0));                    }                }
Send data:



Private View. onClickListener sendListener = new View. onClickListener () {@ Override public void onClick (View v) {String str = mEtMessage. getText (). toString (). trim (); if (mPrintWriter = null) {showToast (Please connect to the server first !); Return;} mPrintWriter. println (str); mPrintWriter. flush (); mEtMessage. setText ();}};



ShowToast (disconnect); try {mBufferReader. close (); mPrintWriter. close (); mSocket. close (); mSocket = null; if (mGetMessageThread! = Null) {mGetMessageThread = null ;}} catch (IOException e) {e. printStackTrace ();}



On the server side, we need a ServerSocket, which is used to receive connection requests. Each time a request is received, a Socket is returned, which can be used to communicate with the client. Note: The server must be always running and can receive many connected programs. The server program must not be closed or collapsed. Therefore, there are many things to consider when designing the server, here we simply process the connection that receives the client request and add it to the list. If we receive the message, we will forward the received message to all other sockets in the list, which is very easy to process.


(1) ServerSocket mServerSocket = new ServerSocket (SERVERPORT); // create a listener to connect to ServerSocket

(2) constantly listen to mServerSocket and use accept () to receive connections. If a connection is detected, start a thread and pass the returned value socket. Then each thread corresponds to a client, you can communicate with the client.

(3) Next, if each thread receives the data, it needs to forward the message to all other users in the customer single-column table.

(4) After the client is disconnected, clear the client socket information.

Start the listening connection and start a thread pool. when listening to connection requests, create a startup thread and put it into the thread pool for running:

        try {            mServerSocket = new ServerSocket(SERVERPORT);            mExecutorService = Executors.newCachedThreadPool();            System.out.println(Server Start...);            Socket client = null;            while (true) {                client = mServerSocket.accept();                mClientList.add(client);                mExecutorService.execute(new ThreadServer(client));            }        } catch (IOException e) {            e.printStackTrace();        }
Receive messages and forward messages in the thread:



    private class ThreadServer implements Runnable {        private Socket mClient;        private BufferedReader mBufferedReader;        private PrintWriter mPrintWriter;        private String mStrMsg;        public ThreadServer(Socket client) throws IOException {            this.mClient = client;            mBufferedReader = new BufferedReader(new InputStreamReader(                    mClient.getInputStream()));            mStrMsg = usr: + this.mClient.getInetAddress() +  connected                    + ,total: + mClientList.size();            sendMessage(mStrMsg);        }        private void sendMessage(String msg) throws IOException {            System.out.println(msg);            for (Socket client : mClientList) {                mPrintWriter = new PrintWriter(client.getOutputStream(), true);                mPrintWriter.println(msg);            }        }        @Override        public void run() {            try {                while (null != (mStrMsg = mBufferedReader.readLine())) {                    if (mStrMsg.trim().equals(exit)) {                        mStrMsg = user: + mClient.getInetAddress() +  exit!                                + total: + (mClientList.size() - 1);                        sendMessage(mStrMsg);                        mPrintWriter = new PrintWriter(                                mClient.getOutputStream(), true);                        mPrintWriter.println(exit);                        mBufferedReader.close();                        mPrintWriter.close();                        mClientList.remove(mClient);                        mClient.close();                        break;                    } else {                        mStrMsg = mClient.getInetAddress() + : + mStrMsg;                        sendMessage(mStrMsg);                    }                }            } catch (SocketException e) {                // e.printStackTrace();            } catch (IOException e) {                e.printStackTrace();            }        }    }



If there is no network foundation, this is still a bit complicated to understand. I have posted the project code below. Let's take a look at it. Using socket is actually very simple, mainly for logic processing.

Note the following points:

(1) network requests cannot be called in the main UI thread after android2.3, And will crash directly. Therefore, handler must be used to send messages for processing.

(2) You may not be able to use the instance code on your machine. SERVER_IP is the local address of the computer on the LAN and needs to be modified by yourself. The android client needs to be connected to the computer so that the client can find the server.




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: 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.