菜鸟笔记
提升您的技术认知

ipc通信方式之localsocket-ag真人游戏

  • 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通信过程如下图

而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所处的命名空间,下图是本地截取的部分输出。

一般两个不同的应用之间如果要相互通信,首先想到的ag真人游戏的解决方案都是利用aidl,这里我们用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/[email protected]

则表明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/[email protected]

则表明testlocalsocketclient已经连接上了testlocalsocketserver,可以给testlocalsocketserver发送消息了。

网站地图