最近做项目,遇到一个需要通过Localsocket通信的问题,实现Library建立local socket服务端,APK实现Local socket客户端,以前自己也做过,直接在网上找的代码,客户端Java,服务器端C,没有问题。这次客户端还是照着之前的做,服务器端同时做的,然后怎么都连接不上,发现他建立Local socket的方式跟我以前的不一样,然后仔细研究了一下才发现,Local socket的实现方式也分好几种情况。
下面就Android App和Linux中关于Local socket的定义分别介绍。
一 ,Android App中的Local socket
1. Android的LocalSocketAddress
先看看关于LocalSocketAddress的两个构造函数:
/**
* The namespace that this address exists in. See also
* include/cutils/sockets.h ANDROID_SOCKET_NAMESPACE_*
*/
public enum Namespace {
/** A socket in the Linux abstract namespace */
ABSTRACT(0),
/**
* A socket in the Android reserved namespace in /dev/socket.
* Only the init process may create a socket here.
*/
RESERVED(1),
/**
* A socket named with a normal filesystem path.
*/
FILESYSTEM(2);
/** The id matches with a #define in include/cutils/sockets.h */
private int id;
Namespace (int id) {
this.id = id;
}
/**
* @return int constant shared with native code
*/
/*package*/ int getId() {
return id;
}
public LocalSocketAddress(String name, Namespace namespace) {
this.name = name;
this.namespace = namespace;
}
public LocalSocketAddress(String name) {
this(name,Namespace.ABSTRACT);
}
可以看到NameSpace有三种:
ABSTRACT:在系统中维护一个socket描述符,不会在系统上建立文件。
FILESYSTEMÿ