0
我正在使用UNIX套接字来促进与Android设备之间的系统级守护进程之间的通信我已经在C中运行了一个应用程序,我已经在Java中运行。我比Java编码器更像C编码器,所以我在尝试从Java端的套接字读取数据时遇到了一些问题。目前,我的代码如下:确定LocalSocket读取大小
try{//Prepare to write the command and read the ACK
InputStream is = receiver.getInputStream();
OutputStream os = receiver.getOutputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
os.write(message.getBytes());
//FIX THIS!! The following assumes that there is a newline-
// terminated chunk of data waiting for us in the buffer. If
// that assumption is wrong, the code will hang. Find some way
// to determine if/how much data is waiting for us in the socket!
String str = in.readLine();
is.close();
os.close();
receiver.close();
return str;
}catch(IOException ex){
Log.e(TAG,(ex.toString()+"\n"));
return null;
}
至于我的评论表明,这种实现工程(ISH),但要求在服务器端套接字代码响应以一个换行符结尾的字符串的非常糟糕的设计缺陷。如果情况并非如此,世界就会结束。
我想弄明白的是,如果有更好的方法来完成这项任务。是否有可能确定是否有任何数据等待在缓冲读取器中读取,如果有,数据的大小是多少?如果没有,有没有更好的方式来读取我不熟悉的Android的Java端UNIX套接字上的数据?
在此先感谢!
谢谢! 我很好奇的另一件事 - 我只注意到InputStream类的available()函数。结合read()给我 while(is.available()!= 0) str + =(char)is.read(); return str; 这似乎工作,但在available()的描述中的“估计”这个词让我有些不知所措 - 如何可靠()? – 2010-07-19 21:21:33
available()== 0并不意味着流结束。 read()== - 1确实意味着。你不会需要可用的()。 – irreputable 2010-07-19 21:41:02
你确定read()== -1是UNIX套接字的流结束吗?我目前的片段是 int readByte = is.read(); while(readByte!= -1)str + =(char)readByte; readByte = is.read(); } 但这看起来在读取-1之前超时。至少,我假设它是超时 - 实际发生的情况是我的应用程序干净地回到主屏幕,并在所有地方记录呕吐物输出。具体来说,它抛出一个LocalSocket正在调用的JNI方法的异常,然后是一个巨大的堆栈跟踪,Dalvik中止以及大量的内存地址映射信息。 – 2010-07-19 22:00:37