2011-09-14 68 views
2

我知道在连接期间需要从服务器获取数据时,有一个很好的变体可以使用Scanner对象。不过,我对下面的代码片段问题:良好的连接建立

public void sendMessage(String message) { 
    try { 
     OutputStream os = socket.getOutputStream(); 

     try { 
      byte[] buffer; 
      buffer = message.getBytes(); 
      os.write(buffer); 
     } finally { 
      os.close(); 
     } 

     InputStream is = socket.getInputStream(); 

     try { 
      StringBuffer data = new StringBuffer(); 
      Scanner in = new Scanner(is); 
      while (in.hasNext()) { 
       data.append(in.next()); 
      } 
      System.out.println(data.toString()); 
     } finally { 
      is.close(); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

我对那里ScannerInputStream获取数据,因为它刚刚开始后,我将消息发送到服务器的代码片段困惑。假设来自服务器的数据在发送消息后立即不在InputStream之内是否公平?

请给我一个建议,在这种情况下从InputStream读取数据的最佳方法是什么以及我应该考虑什么?

回答

0

的代码是无效的。它所做的只是读取尽可能多的输入,而不用阻塞就可以读取。没有暗示读取的内容是完整的消息,或者对应于发送方的单个write()调用等。如果您想要使用TCP/IP中的消息,则必须自己实现它们,并使用长度字前缀,自描述协议,如对象序列化或XML等等。