先貼上LocalSocket的代碼:
//創(chuàng)建對象
LocalSocket localSocket = new LocalSocket();
//連接socketServerSocket
localSocket.connect(new LocalSocketAddress(String addrStr));
獲取localSocket的輸入輸出流:
outputStream = localSocket.getOutputStream();
inputStream = localSocket.getInputStream();
寫入數(shù)據(jù):
outputStream.write("輸入的內(nèi)容".getBytes());
接收數(shù)據(jù):
try {
int readed = inputStream.read();
int size = 0;
byte[] bytes = new byte[0];
while (readed != -1) {
byte[] copy = new byte[500000];
System.arraycopy(bytes, 0, copy, 0, bytes.length);
bytes = copy;
bytes[size++] = (byte) readed;
//以換行符標識成結(jié)束
if ('\n' == (byte) readed) {
String resultStr = new String(bytes, 0, size); break;
}
readed = inputStream.read();
}
} catch (IOException e) {
return false;
}
至此,LocalSocket部分的代碼已經(jīng)完畢了,注意捕獲異常。
LocalServerSocket部分代碼馬上貼上:
//初始化
try {
//socketAddress需跟localSocket地址一致,否則無法連接上
serverSocket = new LocalServerSocket(socketAddress);
} catch (IOException e) {
LoggerHelper.e("Server to establish connection exception:" + e.toString());
e.printStackTrace();
return false;
}
try {
//獲取接收的LocalSocket
localSocket = serverSocket.accept();
//設置緩沖大小
localSocket.setReceiveBufferSize(ConstantConfig.BUFFER_SIZE);
localSocket.setSendBufferSize(ConstantConfig.BUFFER_SIZE);
} catch (IOException e) {
e.printStackTrace();
LoggerHelper.d("Waiting to be linked to a bug,error:" + e.toString());
return false;
}
獲取輸入輸出流一致:
if (localSocket != null) {
try {
inputStream = localSocket.getInputStream();
outputStream = localSocket.getOutputStream();
/** 允許一直接收數(shù)據(jù),一直到連接被斷開,則認為應用端退出,自己也退出 */
while (isLock && receiveData()) ;
} catch (IOException e) {
LoggerHelper.e("Get stream exception:" + e.toString()); e.printStackTrace();
return false;
}
}
已經(jīng)ok啦。。。