Android进程间通信之LocalSocket通信

☆樱花仙子☆ 提交于 2020-03-28 05:03:41

LocalSocket,在Unix域名空间创建的一个套接字(非服务端)。

是对Linux中Socket进行了封装,采用JNI方式调用,实现进程间通信。

具体就是Native层Server和Framework层Client之间进行通信,或在各层次中能使用Client/Server模式实现通信。

在这里通过LocalSocket实现应用之间的通信,可以接收、发送数据,同时将接收到的数据通过activty显示。

Server端:

package com.example.driverexam;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import android.net.Credentials;
import android.net.LocalServerSocket;
import android.net.LocalSocket;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
/**
 * 通过LocalSocket实现
 * @author Administrator
 *
 */
public class ServerFinally implements Runnable{
    private static final String TAG="ServerFinally";
    LocalServerSocket server;
    LocalSocket client;
    PrintWriter os;
    BufferedReader is;
    
    Handler handler;
    
    /**
     * 此处不将连接代码写在构造方法中的原因:
     * 我在activity的onCreate()中创建示例,如果将连接代码 写在构造方法中,服务端会一直等待客户端连接,界面没有去描绘,会一直出现白屏。
     * 直到客户端连接上了,界面才会描绘出来。原因是构造方法阻塞了主线程,要另开一个线程。在这里我将它写在了run()中。
     */
    ServerFinally(Handler handler){
        this.handler=handler;
        
//        try {
//            Log.i(TAG, "Server=======打开服务=========");
//            server=new LocalServerSocket("com.repackaging.localsocket");
//            client=server.accept();
//            Log.i(TAG, "Server=======客户端连接成功=========");
//            Credentials cre=client.getPeerCredentials();
//            Log.i(TAG, "===客户端ID为:"+cre.getUid());
//            os=new PrintWriter(client.getOutputStream());
//            is=new BufferedReader(new InputStreamReader(client.getInputStream()));
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
    }
    
    //发数据
    public void send(String data){
        if (os!=null) {
            os.println(data);
            os.flush();
        }
    }
        
    //接数据
    @Override
    public void run() {
        Log.i(TAG, "Server=======打开服务=========");
        try {
            server=new LocalServerSocket("com.repackaging.localsocket");
        
            
            client=server.accept();
            Log.i(TAG, "Server=======客户端连接成功=========");
            Credentials cre=client.getPeerCredentials();
            Log.i(TAG, "===客户端ID为:"+cre.getUid());
            os=new PrintWriter(client.getOutputStream());
            is=new BufferedReader(new InputStreamReader(client.getInputStream()));
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        
        String result="";
        while(true){
            try {
                result=is.readLine();
                Log.i(TAG, "服务端接到的数据为:"+result);
                //把数据带回activity显示
                Message msg=handler.obtainMessage();
                msg.obj=result;
                msg.arg1=0x11;
                handler.sendMessage(msg);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
    }
    
    public void close(){
        try {
            if (os!=null) {
                os.close();
            }
            if (is!=null) {
                is.close();
            }
            if(client!=null){
                client.close();
            }
            if (server!=null) {
                server.close();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
}

ServerFinallyActivity.java

package com.example.driverexam;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class ServerFinallyActivity extends Activity {
    
    EditText et_serverSend;
    TextView tv_showReceiveData;
    
    ServerFinally server;
    
//    ServerLastly server;
    StringBuffer receiveData=new StringBuffer();
    
    Handler handler=new Handler(new Handler.Callback() {
        
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.arg1==0x11) {
                receiveData.append((String)msg.obj);
                tv_showReceiveData.setText(receiveData);
                receiveData.append("\r\n");
            }
            
            return false;
        }
    });
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        
        setContentView(R.layout.activity_server_finally);
        et_serverSend=(EditText) findViewById(R.id.et_serverSend);
        tv_showReceiveData=(TextView) findViewById(R.id.tv_showReceiveData);
        
        server=new ServerFinally(handler);
        new Thread(server).start();
        
//        server=new ServerLastly(handler);
//        new Thread(server).start();
        
    }

    //发数据
    public void btn_serverSend(View view){
        server.send(et_serverSend.getText().toString()+"");
        et_serverSend.setText("");
    }
    
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        server.close();
    }
        
}

Client端:

ClientFinally.java

package com.fqhx.remoteserviceclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import android.net.LocalSocket;
import android.net.LocalSocketAddress;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
/**
 * 通过LocalSocket实现
 * @author Administrator
 *
 */
public class ClientFinally implements Runnable{
    private static final String TAG="ClientFinally";
    private static final String NAME="com.repackaging.localsocket";
    private int timeout=30000;
    LocalSocket client;
    PrintWriter os;
    BufferedReader is;
    
    Handler handler;
    
    ClientFinally(Handler handler){
        this.handler=handler;
//        client=new LocalSocket();
//        try {
//            client.connect(new LocalSocketAddress(NAME));//连接服务器
//            Log.i(TAG, "Client=======连接服务器成功=========");
//            client.setSoTimeout(timeout);
//            os=new PrintWriter(client.getOutputStream());
//            is=new BufferedReader(new InputStreamReader(client.getInputStream()));
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
    }
    
    //发数据
    public void send(String data){
        if (os!=null) {
            os.println(data);
            os.flush();
        }
    }

    @Override
    public void run() {
        client=new LocalSocket();
        try {
            client.connect(new LocalSocketAddress(NAME));//连接服务器
            Log.i(TAG, "Client=======连接服务器成功=========");
            client.setSoTimeout(timeout);
            os=new PrintWriter(client.getOutputStream());
            is=new BufferedReader(new InputStreamReader(client.getInputStream()));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        String result="";
        while(true){
            try {
                result=is.readLine();
                Log.i(TAG, "客户端接到的数据为:"+result);
                //将数据带回acitvity显示
                Message msg=handler.obtainMessage();
                msg.arg1=0x12;
                msg.obj=result;
                handler.sendMessage(msg);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
    }

    public void close(){
        try {
            if (os!=null) {
                os.close();
            }
            if (is!=null) {
                is.close();
            }
            if(client!=null){
            client.close();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
}

ClientFinallyActivity.java

package com.fqhx.remoteserviceclient;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class ClientFinallyActivity extends Activity {
    
    ClientFinally client;
    EditText et_clientSend;
    TextView tv_showReceiveDataClient;
    
//    ClientLastly client;
    StringBuffer receiveData=new StringBuffer();
    
    Handler handler=new Handler(new Handler.Callback() {
        
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.arg1==0x12) {
                receiveData.append((String)msg.obj);
                tv_showReceiveDataClient.setText(receiveData);
                receiveData.append("\r\n");
            }
            
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_client_finally);
        
        et_clientSend=(EditText) findViewById(R.id.et_clientSend);
        tv_showReceiveDataClient=(TextView) findViewById(R.id.tv_showReceiveDataClient);
        
        client=new ClientFinally(handler);
        new Thread(client).start();
        
//        client=new ClientLastly(handler);
//        new Thread(client).start();
    }

    
    public void btn_clientSend(View view){
        client.send(et_clientSend.getText().toString()+"");
        et_clientSend.setText("");
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        client.close();
    }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!