在Android上使用LocalSocket实现上层Java和底层C++的通

在看Android代码的时候发现有使用LocalSocket,比Java本身的socket效率要高,好像没有经过协议栈,是android自己实现的类似共享内存一样的东东,在传输大量数据的时候就需要用到,比如视频数据,在RIL电话那部分也用到。刚好项目用到视频传输,我试用了一把,果然不错!
public static final String SOCKET_ADDRESS = "socket_cmmb_sim_command";//这个名字要记好,在接受端要用到,可以理解为共享内存的设备文件名。
.....

try {
                LocalServerSocket server = new LocalServerSocket(SOCKET_ADDRESS);
                while (true) {
                    //Log.i(TAG, "begin accept");
                    LocalSocket receiver = server.accept();
                    if (receiver != null) {
                        InputStream input = receiver.getInputStream();

byte[] bytes = new byte[4];
                        int size = input.read(bytes, 0, 4);
                        if(size!=4) Log.i(TAG, "received command len:" + String.valueOf(size));

int cmd_len = ((bytes[0] & 0xFF) << 24)|((bytes[1] & 0xFF) << 16)
                                |((bytes[2] & 0xFF) << 8)|(bytes[3] & 0xFF);

Log.i(TAG, "received cmd_len:"+String.valueOf(cmd_len));
                        if(cmd_len>0){
                            byte[] ArrayOfByte = new byte[cmd_len];
                            size = input.read(ArrayOfByte, 0, cmd_len);
                            Log.i(TAG, "received data len:" + String.valueOf(size));
                            Parcel parcel = Parcel.obtain();
                            parcel.unmarshall(ArrayOfByte, 0, ArrayOfByte.length);
                            parcel.setDataPosition(0);
                            processRequest(receiver,parcel);
                        }

}
                }
            } catch (IOException e) {
                Log.e(getClass().getName(), e.getMessage());
            }
        private void sendResult(LocalSocket paramLocalSocket, Parcel paramParcel) throws IOException{
            byte[] arrayOfByte1 = new byte[4];
            byte[] arrayOfByte2 = paramParcel.marshall();
            Log.i(TAG, "enter sendResult!");
            arrayOfByte1[0] = 0;
            arrayOfByte1[1] = 0;
            arrayOfByte1[2] = (byte)(arrayOfByte2.length >> 8 & 0xFF);
            arrayOfByte1[3] = (byte)(arrayOfByte2.length & 0xFF);

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/pxdyz.html