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

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

java - Socketchannel always null

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

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

1 Answer

0 votes
by (71.8m points)
    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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...