Android中Socket編程
LocalServerSocket介紹
LocalServerSocket是屬于Android系統(tǒng)內(nèi)置的一個類蒸辆,屬于net包下贱案,類似java中的serversocket類的功能暇榴。
Non-standard class for creating an inbound UNIX-domain socket in the Linux abstract namespace.
這個類比較簡單举户,構(gòu)造方法有兩個:
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 :獲取當(dāng)前的連接描述婿崭;
- accept:接收一個localsocket拨拓;
- getFileDescriptor:獲取當(dāng)前連接的文件描述符;
- close:關(guān)閉socket服務(wù)氓栈;
查看LocalServerSocket源碼可知:
- 在構(gòu)造方法中已經(jīng)默認(rèn)設(shè)置了socket的類型為:LocalSocket.SOCKET_STREAM;
- 綁定了傳入的namespace并且監(jiān)聽渣磷;
- 使用的是LocalSocketAddress傳入namespace生成LocalSocketAddress進(jìn)行操作;
- 以上操作都是通過LocalSocketImpl【待分析】對象進(jìn)行的授瘦;
總結(jié)
本類內(nèi)容比較簡單醋界,主要實(shí)現(xiàn)方式都在LocalSocketImpl中,下次分析提完。
LocalSocket介紹
This class and the streams returned from it may be used from multiple threads.
內(nèi)容基本同LocalScoket形纺,主要功能也是通過LocalSocketImpl實(shí)現(xiàn)的。
代碼
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); // 客戶端發(fā)送數(shù)據(jù)
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
public void receiver() {
new Thread() {
@Override
public void run() {
try {
InputStream inputStream = localSocketReceiver.getInputStream();
int ret = inputStream.read(); // 獲取結(jié)果
Log.e("測試結(jié)果 ", "" + ret);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}