Android中Socket编程
LocalServerSocket介绍
LocalServerSocket是属于Android系统内置的一个类,属于net包下,类似java中的serversocket类的功能。
Non-standard class for creating an inbound UNIX-domain socket in the Linux abstract namespace.
这个类比较简单,构造方法有两个:
LocalServerSocket(String name)
Creates a new server socket listening at specified name.
LocalServerSocket(FileDescriptor fd)
Create a LocalServerSocket from a file descriptor that's already been created and bound.
一般使用第一个即可;
本类中方法只有四个,分别是:
- getLocalSocketAddress :获取当前的连接描述;
- accept:接收一个localsocket;
- getFileDescriptor:获取当前连接的文件描述符;
- close:关闭socket服务;
查看LocalServerSocket源码可知:
- 在构造方法中已经默认设置了socket的类型为:LocalSocket.SOCKET_STREAM;
- 绑定了传入的namespace并且监听;
- 使用的是LocalSocketAddress传入namespace生成LocalSocketAddress进行操作;
- 以上操作都是通过LocalSocketImpl【待分析】对象进行的;
总结
本类内容比较简单,主要实现方式都在LocalSocketImpl中,下次分析。
LocalSocket介绍
This class and the streams returned from it may be used from multiple threads.
内容基本同LocalScoket,主要功能也是通过LocalSocketImpl实现的。
代码
final static String SOCKET_ADDRESS = "LocalSocketAddress";
LocalSocket localSocketSender, localSocketReceiver;
LocalServerSocket localServerSocket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
localServerSocket = new LocalServerSocket(SOCKET_ADDRESS);
localSocketSender = new LocalSocket();
localSocketSender.connect(new LocalSocketAddress(SOCKET_ADDRESS));
localSocketReceiver = localServerSocket.accept();
send();
receiver();
} catch (IOException e) {
e.printStackTrace();
}
}
public void send() {
new Thread() {
@Override
public void run() {
try {
OutputStream outputStream = localSocketSender.getOutputStream();
outputStream.write(60); // 客户端发送数据
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
public void receiver() {
new Thread() {
@Override
public void run() {
try {
InputStream inputStream = localSocketReceiver.getInputStream();
int ret = inputStream.read(); // 获取结果
Log.e("测试结果 ", "" + ret);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}