Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to send an EHLO command to an SMTP server. 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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
363 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

You put the SMTP_EHLO into the buffer, but you must flip() the buffer before writing it. Otherwise, you are writing nothing to the socket channel. From the 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.

And from 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...