Android进程间通信LocalSocket

       进程间通信,肯定会有读写等耗时操作,所以要把代码写在子线程中。

一、服务端LocalServerSocket

       1、创建服务端LocalServerSocket的对象

server = new LocalServerSocket ("ysy_data");
       2、监听连接,获取服务端LocalSocket对象。

client = server.accept ();
       3、获取输入输出流。

os = new PrintWriter (client.getOutputStream ());
is = new BufferedReader (new InputStreamReader (client.getInputStream ()));
       4、接收客户端发过来的数据

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 ();
}
     5、发送数据

//发数据
public void send (String data) {
    if (os != null) {
        os.println (data);
        os.flush ();
    }
}
     6、关闭流,释放资源

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 ();
}
二、客户端LocalSocket

     1、创建客户端对象

client = new LocalSocket ();
     2、连接服务端

client.connect (new LocalSocketAddress (NAME));
     3、获取输入输出流

os = new PrintWriter (client.getOutputStream ());
is = new BufferedReader (new InputStreamReader (client.getInputStream ()));
     4、读取服务端发送过来的数据

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 ();
    }
}
     5、发送数据

//发数据
public void send (String data) {
    if (os != null) {
        os.println (data);
        os.flush ();
    }
}
     6、关闭流,释放资源

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 ();
}
三、参考文章

http://www.cnblogs.com/Joanna-Yan/p/4708400.html

猜你喜欢

转载自blog.csdn.net/yangshuangyue/article/details/59574745