人生有八苦:生,老,病,死,爱别离,怨长久,求不得,放不下。
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下。具体如下
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发送消息了。
网友评论