我正在尝试向SMTP服务器发送EHLO命令。连接成功,但我似乎无法从中读取任何数据:
ByteBuffer byteBuffer = null;
try {
socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("host", 25));
socketChannel.configureBlocking(true);
byteBuffer = ByteBuffer.allocateDirect(4 * 1024);
} catch (Exception e) {
e.printStackTrace();
}
try {
byteBuffer.clear();
socketChannel.write(byteBuffer.put(SMTP_EHLO.getBytes()));
byteBuffer.flip();
socketChannel.read(byteBuffer);
byteBuffer.get(subStringBytes);
String ss = new String(subStringBytes);
System.out.println(byteBuffer);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}print语句的输出始终为\u000(null)
发布于 2012-08-09 03:52:34
socketChannel.write(byteBuffer.put(SMTP_EHLO.getBytes()));您可以将SMTP_EHLO put到缓冲区中,但在写入之前必须对缓冲区执行flip()操作。否则,您将不向套接字通道写入任何内容。在SocketChannel Javadoc中:
尝试向通道写入最多r个字节,其中r是调用此方法时缓冲区中剩余的字节数,即
src.remaining()。
来自Buffer#remaining()
public final int remaining()
返回当前位置和限制之间的元素数。
所以,在byteBuffer.put(...)当前位置==限制之后。
https://stackoverflow.com/questions/11871681
复制相似问题