有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Socketchannel始终为空

我正在尝试向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)


共 (1) 个答案

  1. # 1 楼答案

        socketChannel.write(byteBuffer.put(SMTP_EHLO.getBytes()));
    

    您可以put将SMTP\u EHLO写入缓冲区,但必须flip()在写入缓冲区之前。否则,将不向套接字通道写入任何内容。从SocketChannelJavadoc:

    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(...)之后,当前位置==限制