开发者

Determining LocalSocket read size

开发者 https://www.devze.com 2023-01-07 19:07 出处:网络
I\'m using a UNIX socket to facilitate communication on and Android device between a system level daemon I\'ve got running in C and an application I\'ve got running in Java.I\'m much more of a C coder

I'm using a UNIX socket to facilitate communication on and Android device between a system level daemon I've got running in C and an application I've got running in Java. I'm much more of a C coder than a Java coder, so I'm having some issues when trying to read in data from the socket on the Java side. Currently, my code is as follows:

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!
  Stri开发者_如何学Pythonng str = in.readLine();

  is.close();
  os.close();
  receiver.close();
     return str;
 }catch(IOException ex){
  Log.e(TAG,(ex.toString()+"\n"));
  return null;
 }

As my comment indicates, this implementation works(ish), but has the very bad design flaw of requiring that the server side socket code responds with a newline terminated string. If that's not the case, the world ends.

What I'm trying to figure out is if there is a better means of accomplishing this task. Is it possible to determine if there is any data waiting to be read in a buffered reader, and if so, what the size of that data is? If not, is there a better way of reading in data over a UNIX socket on the Java side of Android that I'm not familiar with?

Thanks in advance!


if the protocol requires a newline, your impl is appropriate. the code SHOULD be blocked until a newline is read. what else can you do but wait?

of course, usually you don't want to wait forever, you need a timeout. see Socket.setSoTimeout()

if a newline is not necessarily given by server, and you just want to read any data as soon as available, use InputStream.read()

0

精彩评论

暂无评论...
验证码 换一张
取 消