代码之家  ›  专栏  ›  技术社区  ›  Jordan Wills

确定本地套接字读取大小

  •  0
  • Jordan Wills  · 技术社区  · 14 年前

    我正在使用一个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;
     }
    

    我想弄清楚的是,是否有更好的方法来完成这项任务。是否可以确定缓冲读取器中是否有任何数据等待读取,如果有,该数据的大小是多少?如果没有,有没有更好的方法通过Android Java端的UNIX套接字读取数据,而我对此并不熟悉?

    1 回复  |  直到 14 年前
        1
  •  0
  •   irreputable    14 年前

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

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

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