先贴上LocalSocket的代码:
//创建对象
LocalSocket localSocket = new LocalSocket();
//连接socketServerSocket
localSocket.connect(new LocalSocketAddress(String addrStr));
获取localSocket的输入输出流:
outputStream = localSocket.getOutputStream();
inputStream = localSocket.getInputStream();
写入数据:
outputStream.write("输入的内容".getBytes());
接收数据:
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;
//以换行符标识成结束
if ('\n' == (byte) readed) {
String resultStr = new String(bytes, 0, size); break;
}
readed = inputStream.read();
}
} catch (IOException e) {
return false;
}
至此,LocalSocket部分的代码已经完毕了,注意捕获异常。
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();
/** 允许一直接收数据,一直到连接被断开,则认为应用端退出,自己也退出 */
while (isLock && receiveData()) ;
} catch (IOException e) {
LoggerHelper.e("Get stream exception:" + e.toString()); e.printStackTrace();
return false;
}
}
已经ok啦。。。
网友评论