[英]Socketchannel always null
我正在尝试将EHLO命令发送到SMTP服务器。 连接成功,但是我似乎无法从中读取任何数据:
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();
}
打印语句的输出始终为\\ u000(null)
socketChannel.write(byteBuffer.put(SMTP_EHLO.getBytes()));
您put
SMTP_EHLO放入缓冲区中,但是必须在写入缓冲区之前将它flip()
。 否则,您什么都不写到套接字通道。 从SocketChannel
Javadoc:
尝试将最多r个字节写入通道,其中r是调用此方法时缓冲区中剩余的字节数,即
src.remaining()
。
从Buffer#remaining()
:
public final int remaining()
返回当前位置和限制之间的元素数。
因此,在byteBuffer.put(...)
当前位置==限制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.