java - 套接字 channel 始终为空

标签 java sockets

我正在尝试将 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/

相关文章:

java - Java中的while循环错误

java - 表中两个外键的组合,不能多次插入

node.js - 定期检查和清理服务器中的文件

javascript - (Node js) 如何向特定用户发送通知?

c++ - 连接到由 Boost.Asio 创建的域套接字时权限被拒绝

java - 我可以使用 jfk 的 Map 1 键到多值吗?

java - 一个 JFrame 和两个 JPanel

java - java方法中需要分号

java - 使用 NIO 进行套接字编程

c - 用C语言制作我自己的视频发送网络应用程序