Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 确定本地套接字读取大小_Java_Android_Sockets - Fatal编程技术网

Java 确定本地套接字读取大小

Java 确定本地套接字读取大小,java,android,sockets,Java,Android,Sockets,我正在使用一个UNIX套接字来促进在Android设备上的通信,这个设备是用C语言运行的系统级守护进程和用Java语言运行的应用程序。我更像是一个C编码员而不是Java编码员,所以我在尝试从Java端的套接字读入数据时遇到了一些问题。目前,我的代码如下: try{//Prepare to write the command and read the ACK InputStream is = receiver.getInputStream(); OutputStream os = rece

我正在使用一个UNIX套接字来促进在Android设备上的通信,这个设备是用C语言运行的系统级守护进程和用Java语言运行的应用程序。我更像是一个C编码员而不是Java编码员,所以我在尝试从Java端的套接字读入数据时遇到了一些问题。目前,我的代码如下:

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套接字读取数据,而我对此并不熟悉


提前谢谢

如果协议需要换行符,则您的impl是合适的。在读取换行符之前,应阻止代码。除了等待,你还能做什么

当然,通常你不想永远等待,你需要一个暂停。请参见
Socket.setSoTimeout()


如果服务器不一定给出换行符,并且您只想尽快读取任何可用数据,请使用
InputStream.read()

谢谢!还有一件事我很好奇——我刚刚注意到InputStream类的可用()函数。将其与read()相结合,可以得到while(is.available()!=0)str+=(char)is.read();返回str;这似乎有效,但available()描述中的“estimated”一词让我有点怀疑-available()的可靠性有多高?available()==0并不意味着流的结束。read()=-1的意思是。您可能不需要available()。您确定read()=-1是UNIX套接字的流结束吗?我当前的代码段是int readByte=is.read();虽然(readByte!=-1){str+=(char)readByte;readByte=is.read();}但这似乎在读取-1之前超时。至少,我假设它超时了——实际发生的是,我的应用程序clean崩溃回主屏幕,并记录到处都是的cat呕吐输出。具体地说,它在LocalSocket调用的JNI方法上抛出了一个异常,随后是一个巨大的堆栈跟踪、Dalvik中止和大量内存地址映射信息.bwar,很抱歉格式太草率——仍然是堆栈溢出的新手,我还没有掌握注释中格式化代码的诀窍,yettimeout可能在流结束之前出现。也可能出现其他例外情况。您可以
尝试捕获
异常并决定如何处理它们。