1. 程式人生 > >IPC通訊方式之LocalSocket

IPC通訊方式之LocalSocket

人生有八苦:生,老,病,死,愛別離,怨長久,求不得,放不下。

LocalSocket是什麼

在弄清LocalSocket是什麼之前,有必要先了解下Socket是什麼。Socket通常翻譯為套接字,它是為了方便讓兩臺機器能互相通訊的一套技術,該套技術封裝好了繁瑣的TCP/IP協議,向外提供出簡單的API簡化了通訊實現的過程,其可以實現不同層面,不同應用,跨程序跨網路的通訊。依據Socket提供的資料傳輸特性可分為如下幾個大類:

  • Stream socket: 提供雙向、有序、可靠、非重複的資料通訊。大致可以認為它封裝的TCP通訊協議。
  • Datagram socket: 提供雙向資料通訊,資料不一定按順序到達。大致可以認為它封裝的是UDP通訊協議。
  • Sequential socket: 提供雙向、有序、可靠資料通訊,資料包有最大限制,並且必須把這個包完整的接受才能進行讀取。
  • Raw socket: 提供相對TCP/UDP而言較下層的通訊協議訪問,如果使用非TCP/UDP的通訊協議可以使用該型別的socket。

socket通訊過程如下圖
socket通訊過程示意圖

而Android中的LocalSocket是基於UNIX-domain Socket的,UNIX-domain Socket是在Socket的基礎上衍生出來的一種IPC通訊機制,因此LocalSocket解決的是同一臺主機上不同程序間互相通訊的問題。其相對於網路通訊使用的socket不需要經過網路協議棧,不需要打包拆包、計算校驗,自然的執行效率也高。與大名鼎鼎的binder機制作用一樣,都在Android系統中作為IPC通訊手段被廣泛使用。

在去程式碼看看
frameworks/base/core/java/android/net/LocalSocket.java

public class LocalSocket implements Closeable {

    private final LocalSocketImpl impl;
    private volatile boolean implCreated;
    private LocalSocketAddress localAddress;
    private boolean isBound;
    private boolean isConnected;
    private
final int sockType; /** unknown socket type (used for constructor with existing file descriptor) */ /* package */ static final int SOCKET_UNKNOWN = 0; /** Datagram socket type */ public static final int SOCKET_DGRAM = 1; /** Stream socket type */ public static final int SOCKET_STREAM = 2; /** Sequential packet socket type */ public static final int SOCKET_SEQPACKET = 3; // ...

從上述程式碼片段引出了幾個重要的相關類:

  • LocalSocketImpl: 如果看過JDK原始碼中的Socket模組,其中有一個SocketImpl類,客戶端socket和服務端socket都是通過SocketImpl創建出來的。對比來看LocalSocketImpl的作用跟SocketImpl類似,不過這裡還差一個服務端socket,檢視LocalSocketImpl的類註釋,

    /**
     Socket implementation used for android.net.LocalSocket and
     android.net.LocalServerSocket. Supports only AF_LOCAL sockets.
     */
     class LocalSocketImpl {

    類註釋裡清楚的闡述了LocalSocketImpl的作用,它是LocalSocket和LocalServerSocket的實現類,並且只支援AF_LOCAL型別的socket,而AF_LOCAL就是UNIX域的本地socket型別。這裡又出現了一個重要類LocalServerSocket,它就是差的那個服務端socket.

  • LocalServerSocket: 服務端的socket。

  • LocalSocketAddress: AF_LOCAL型別socket的地址,做為LocalSocket和 LocalServerSocket互相通訊的標示。這個標示可以放在三個不同的namespace下。具體如下

    ABSTRACT linux 抽象名稱空間
    RESERVED Android系統預定的名稱空間,其路徑在/dev/socket下
    FILESYSTEM 傳統的檔案系統名稱空間

    Android系統可以通過命令

    adb shell netstat -apn

    檢視socket所處的名稱空間,下圖是本地擷取的部分輸出。
    socket-地址空間

LocalSocket通訊例項

一般兩個不同的應用之間如果要相互通訊,首先想到的解決方案都是利用AIDL,這裡我們用LocalSocket來實現。通過該例子來實踐下LocalSocket。
先看看執行效果圖。
LocalSocket例項

TestLocalSocketServer和TestLocalSocketClient是不同的兩個應用,我們從TestLocalSocketClient輸入一個字串,然後在TestLocalSocketServer顯示出來。

TestLocalSocketServer核心程式碼:

public class ServerActivity extends Activity {

    private LocalServerSocket mServerSocket = null;
    private LocalSocket mSocket = null;
    private TextView mShowMsg = null;
    private InputStream mInputStream = null;
    private static final String SOCKET_NAME = "com.azhengye.testsocket";
    private static final String TAG = "azhengye-Socket";

    private final Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            String dispMesg = (String) msg.obj;
            mShowMsg.setText(dispMesg);
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.replay_btn);
        mShowMsg = (TextView) findViewById(R.id.display_msg);
        createServerSocket();// 建立LocalServerSocket
        new Thread(new Runnable() {
            @Override
            public void run() {
                acceptMsg();//必須要在子執行緒裡接收訊息
            }
        }).start();
    }

    private void createServerSocket() {
        if (mServerSocket == null) {
            try {
                /**注意這裡new出LocalServerSocket的同時,系統層已經同步做了bind和listen。
                 * 我們看看new的過程:
                 * public LocalServerSocket(String name) throws IOException {
                 *       impl = new LocalSocketImpl();
                 *       impl.create(LocalSocket.SOCKET_STREAM);
                 *       localAddress = new LocalSocketAddress(name);
                 *       impl.bind(localAddress);
                 *       impl.listen(LISTEN_BACKLOG);
                 * }
                 */
                mServerSocket = new LocalServerSocket(SOCKET_NAME);
            } catch (IOException ex) {
                throw new RuntimeException(
                        "Error binding to local socket " + ex);
            }
        }
    }

    private void acceptMsg() {
        try {
            mSocket = mServerSocket.accept();//accept是個阻塞方法,這就是必須要在子執行緒接收訊息的原因。
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        while (true) {
            try {
                byte[] buffer = new byte[1024];
                mInputStream = mSocket.getInputStream();
                int count = mInputStream.read(buffer);
                String key = new String(Arrays.copyOfRange(buffer, 0, count));
                Log.d(TAG, "ServerActivity mSocketOutStream==" + key);
                if ("stop".equals(key)) {
                    closeSocketResource();
                    break;
                }
                Message msg = mHandler.obtainMessage();
                msg.obj = key;
                msg.sendToTarget();
            } catch (IOException e) {
                Log.d(TAG, "exception==" + e.fillInStackTrace().getMessage());
                e.printStackTrace();
            }
        }
    }

    private void closeSocketResource() {
        closeSlient(mInputStream);
        closeSlient(mSocket);
        try {
            if (mServerSocket != null) {
                mServerSocket.close();
                mServerSocket = null;
            }
        } catch (IOException ex) {
            Log.e(TAG, "Failed closing ServerSocket" + ex.fillInStackTrace());
        }
    }

    private void closeSlient(Closeable closeable){
        try {
            if (closeable != null) {
                closeable.close();
                closeable = null;
            }
        } catch (IOException ex) {
            Log.e(TAG, "Failed closing : " + closeable);
        }
    }
}

啟動TestLocalSocketServer使用命令:

adb shell netstat -apn|grep testsocket

輸出

unix  2      [ ACC ]     STREAM     LISTENING       898034 12421/com.example.te@com.azhengye.testsocket

則表明TestLocalSocketServer已經就緒,等待客戶端socket接入傳送訊息了。

TestLocalSocketClient核心程式碼:

public class ClientActivity extends Activity implements OnClickListener{
    private LocalSocket mSocket;
    private OutputStream mOut;
    private EditText mEditText = null;
    private static final String SOCKET_NAME = "com.azhengye.testsocket";//這裡必須要跟TestLocalSocketServer中定義的一樣
    private static final String TAG = "azhengye-Socket";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        connect();
        mEditText = (EditText) findViewById(R.id.input_msg);
        findViewById(R.id.replay_btn).setOnClickListener(this);
        findViewById(R.id.stop_btn).setOnClickListener(this);
    }

    private boolean connect() {
        if (mSocket != null) {
            return true;
        }
        try {
            mSocket = new LocalSocket();//建立LocalSocket,模擬客戶端
            LocalSocketAddress address = new LocalSocketAddress(SOCKET_NAME,
                    LocalSocketAddress.Namespace.ABSTRACT);
            mSocket.connect(address);//連線TestLocalSocketServer
        } catch (IOException ex) {
            return false;
        }
        return true;
    }

    private boolean writeCommand(String cmdString) {
        final byte[] cmd = cmdString.getBytes();
        final int len = cmd.length;
        try {
            mOut = mSocket.getOutputStream();
            mOut.write(cmd, 0, len);
            Log.i(TAG, "ClientActivity write " + new String(cmd));
        } catch (IOException ex) {
            Log.e(TAG, "ClientActivity write error:" + ex.fillInStackTrace());
            return false;
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.replay_btn:
                writeCommand(mEditText.getText().toString());
                break;
            case R.id.stop_btn:
                writeCommand("stop");
                break;
            default:
                break;
        }

    }
}

啟動TestLocalSocketClient使用命令:

adb shell netstat -apn|grep testsocket

輸出

unix  3      [ ]         STREAM     CONNECTED       902376 12421/com.example.te@com.azhengye.testsocket

則表明TestLocalSocketClient已經連線上了TestLocalSocketServer,可以給TestLocalSocketServer傳送訊息了。