我知道在连接期间需要从服务器获取数据时,有一个很好的变体可以使用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();
}
}
我对那里Scanner
从InputStream
获取数据,因为它刚刚开始后,我将消息发送到服务器的代码片段困惑。假设来自服务器的数据在发送消息后立即不在InputStream
之内是否公平?
请给我一个建议,在这种情况下从InputStream
读取数据的最佳方法是什么以及我应该考虑什么?
非常感谢!我现在明白了,需要找到更多关于阻塞和非阻塞模式的信息。 – teoREtik