我正在尝试将 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()));
您将
SMTP_EHLO 放入缓冲区,但在写入缓冲区之前必须flip()
缓冲区。否则,您不会向套接字 channel 写入任何内容。来自SocketChannel
Javadoc:
An attempt is made to write up to r bytes to the channel, where r is the number of bytes remaining in the buffer, that is,
src.remaining()
, at the moment this method is invoked.
来自Buffer#remaining()
:
public final int remaining()
Returns the number of elements between the current position and the limit.
因此,在 byteBuffer.put(...)
当前位置 == limit 之后。
关于java - 套接字 channel 始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11871681/