简体   繁体   English

套接字通道始终为null

[英]Socketchannel always null

I'm trying to send an EHLO command to an SMTP server. 我正在尝试将EHLO命令发送到SMTP服务器。 The connection succeeds, but I can't seem to read any data from it: 连接成功,但是我似乎无法从中读取任何数据:

 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();
    }

The output of the print statement is always \\u000(null) 打印语句的输出始终为\\ u000(null)

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

You put the SMTP_EHLO into the buffer, but you must flip() the buffer before writing it. put SMTP_EHLO放入缓冲区中,但是必须写入缓冲区之前将它flip() Otherwise, you are writing nothing to the socket channel. 否则,您什么都不写到套接字通道。 From the SocketChannel Javadoc: 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. 尝试将最多r个字节写入通道,其中r是调用此方法时缓冲区中剩余的字节数,即src.remaining()

And from Buffer#remaining() : Buffer#remaining()

public final int remaining()

Returns the number of elements between the current position and the limit. 返回当前位置和限制之间的元素数。

So, after byteBuffer.put(...) current position == limit. 因此,在byteBuffer.put(...)当前位置==限制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM