Android IPC Mechanism (5) Use Socket to implement cross-process chat programs

Source: Internet
Author: User

Android IPC Mechanism (5) Use Socket to implement cross-process chat programs
1. Socket Introduction

Socket, also known as "Socket", is an abstraction layer between the application layer and the transport layer, it abstracts the complex operations on the TCP/IP layer into several simple interfaces for the application layer to call and Implement Process Communication in the network. It is divided into Stream sockets and data packet sockets, which correspond to the TCP and UDP protocols of the network transmission control layer respectively. TCP is a connection-oriented, reliable, and byte stream-based transport layer communication protocol. It uses the three-way handshake protocol to establish a connection and provides a timeout retransmission mechanism with high stability. UDP is a connectionless protocol that does not guarantee the reliability of transmitted data packets. It is suitable for transmitting a small amount of data at a time. The application layer is responsible for the reliability of UDP transmission. In an environment with unsatisfactory network quality, UDP packet loss may be serious. However, due to the characteristics of UDP: it is not a connection protocol, so it has the advantages of low resource consumption and high processing speed. Therefore, generally, most audio, video, and common data are transmitted using UDP.

We can also see that different user processes communicate through sockets, so Socket is also an IPC method. Next we will use the TCP Service to implement a simple chat program.

2. Implement the chat program server Configuration

First, we will implement the server. Of course, to use Socket, We need to declare the following permissions in AndroidManifest. xml:

<code class="hljs xml">   <uses-permission android:name="android.permission.INTERNET">  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission></uses-permission></code>

We need to implement a remote Service as the server of the chat program. Configure the service in the AndroidManifest. xml file:

<code class="hljs xml">         <service android:name=".SocketServerService" android:process=":remote"></service></code>
Implement Service

Next we will establish a TCP Service in the thread when the Service is started. We listen on port 8688 and wait for the client to connect. A Socket will be generated when the client connects. Each time you create a Socket, you can communicate with different clients. When the client is disconnected, the server also closes the Socket and ends the call thread. The server first sends a message to the client: "Hello, I am the server", receives the message from the client, processes the received message, and returns it to the client.

Package com. example. liuwangshu. moonsocket; import android. app. service; import android. content. intent; import android. OS. IBinder; import android. text. textUtils; import android. util. log; 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; public class SocketServerService extends Service {private boolean isServiceDestroyed = false; @ Override public void onCreate () {new Thread (new TcpServer ()). start (); super. onCreate () ;}@ Override public IBinder onBind (Intent intent) {// TODO: Return the communication channel to the service. throw new UnsupportedOperationException ("Not yet implemented");} private class TcpServer imple Ments Runnable {@ Override public void run () {ServerSocket serverSocket; try {// listen to port 8688 serverSocket = new ServerSocket (8688);} catch (IOException e) {return ;} while (! IsServiceDestroyed) {try {// receives the client request and blocks it until the final Socket client = serverSocket is received. accept (); new Thread () {@ Override public void run () {try {responseClient (client);} catch (IOException e) {e. printStackTrace ();}}}. start ();} catch (IOException e) {e. printStackTrace () ;}}} private void responseClient (Socket client) throws IOException {// used to receive client messages BufferedReader in = new BufferedRead Er (new InputStreamReader (client. getInputStream (); // used to send the message PrintWriter out = new PrintWriter (new BufferedWriter (new OutputStreamWriter (client. getOutputStream (), true); out. println ("Hello, I am a server"); while (! IsServiceDestroyed) {String str = in. readLine (); Log. I ("moon", "received information from the client" + str); if (TextUtils. isEmpty (str) {// The client is disconnected from Log. I ("moon", "client disconnected"); break;} String message = "received client information:" + str; // process the message received from the client and send it to the client out. println (message);} out. close (); in. close (); client. close () ;}@ Override public void onDestroy () {isServiceDestroyed = true; super. onDestroy ();}}
3. Implement the chat client

The client Activity starts the server in the onCreate method and starts the thread to connect to the Socket of the server. To ensure the connection is successful, the timeout reconnection policy is adopted, and the connection will be re-established every time the connection fails. After the connection is successful, the client will receive the message "Hello, I am the server" sent by the server. We can also enter a character in EditText and send it to the server.

Package com. example. liuwangshu. moonsocket; import android. content. intent; import android. OS. systemClock; import android. support. v7.app. appCompatActivity; import android. OS. bundle; import android. text. textUtils; import android. view. view; import android. widget. button; import android. widget. editText; import android. widget. textView; import java. io. bufferedReader; import java. io. bufferedWriter; import java. io. IOExc Eption; import java. io. inputStreamReader; import java. io. outputStreamWriter; import java. io. printWriter; import java.net. socket; public class SocketClientActivity extends AppCompatActivity {private Button bt_send; private EditText et_receive; private Socket mClientSocket; private PrintWriter response; private TextView TV _message; @ Override protected void onCreate (Bundle upload) {super. OnCreate (savedInstanceState); setContentView (R. layout. activity_socket); initView (); Intent service = new Intent (this, SocketServerService. class); startService (service); new Thread () {@ Override public void run () {connectSocketServer ();}}. start ();} private void initView () {et_receive = (EditText) findViewById (R. id. et_receive); bt_send = (Button) findViewById (R. id. bt_send); TV _message = (TextView) This. findViewById (R. id. TV _message); bt_send.setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {final String msg = et_receive.getText (). toString (); // send the message if (! TextUtils. isEmpty (msg) & null! = MPrintWriter) {mPrintWriter. println (msg); TV _message.setText (TV _message.getText () + "\ n" + "client:" + msg); et_receive.setText ("");}}});} private void connectSocketServer () {Socket socket = null; while (socket = null) {try {// Select Port 8688 Socket = new Socket ("localhost ", 8688); mClientSocket = socket; mPrintWriter = new PrintWriter (new BufferedWriter (new OutputStreamWriter (socket. getOutp UtStream (), true);} catch (IOException e) {SystemClock. sleep (1000) ;}try {// receives messages from the server BufferedReader br = new BufferedReader (new InputStreamReader (socket. getInputStream (); while (! IsFinishing () {final String msg = br. readLine (); if (msg! = Null) {runOnUiThread (new Runnable () {@ Override public void run () {TV _message.setText (TV _message.getText () + "\ n" + "server: "+ msg) ;}};}} mPrintWriter. close (); br. close (); socket. close ();} catch (IOException e) {e. printStackTrace ();}}}

The layout is simple (activity_socket.xml ):

<Code class = "hljs xml"> <! -- {Cke_protected} {C} % 3C! % 2D % 2D % 3 Fxml % 20 version % 3D % 221.0% 20 encoding % 3D % 22utf-8% 22% 3F % 2D % 2D % 3E --> <relativelayout android: layout_height = "match_parent" android: layout_width = "match_parent" xmlns: android = "http://schemas.android.com/apk/res/android"> <textview android: id = "@ + id/TV _message" android: layout_height = "400dp" android: layout_width = "match_parent"> <linearlayout android: Layout = "true" android: layout_height = "50dp" android: layout_width = "match_parent" android: orientation = "horizontal"> <edittext android: id = "@ + id/et_receive" android: layout_height = "match_parent" android: layout_weight = "2" android: layout_width = "0dp"> </edittext> </linearlayout> </textview> </relativelayout> </code> <button android: id = "@ + id/bt_send" android: layout_height = "match_parent" android: layout_weight = "1" android: layout_width = "0dp" android: text = "send messages to the server"> <code class = "hljs xml"> </code> </button>
4. Run the chat program

Run the program. We can see that the client and the server are two processes:

The client will first receive a message from the server: "Hello, I am the server". Then we will send a message to the server, "What is my life ". At this time, the server receives this message and returns it to the client after processing:

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