0

I want to determine port whether open.

InetSocketAddress address = new InetSocketAddress("www.google.com", 80);
Selector selector = Selector.open();
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
socketChannel.connect(address);
socketChannel.register(selector, SelectionKey.OP_WRITE);
int result = selector.select();
System.out.println(result);

If the port is not open, think I look the same it return 0, but when the port is open,it also return 0,I expect it can return 1.

Imran
  • 429
  • 9
  • 23
firebroo
  • 85
  • 3
  • Don't know anything about this, but could it be because you've specified configureBlocking(false) - does that mean the operation is asynchronous and you don't know when it will end? – RenniePet Oct 19 '14 at 12:20
  • I think it will be return 1 when execute this code ,because write channel is ready.but it return 0,so i'm so Confused.@RenniePet – firebroo Oct 19 '14 at 12:30
  • why other answer was deleted? – firebroo Oct 19 '14 at 23:13
  • Because it wasn't an answer, just an unsupported assertion that @baconoverlord knew the answer. As your problem doesn't really take pages to explain at all, even the assertion remains dubious. He also cites an obsolete and discredited source. – user207421 Oct 20 '14 at 02:25

1 Answers1

2

It's because you're selecting for the wrong event. You should have registered the channel for OP_CONNECT. Then, when you get it, call finishConnect(), and if it returns true deregister OP_CONNECT and register whatever event you're interested in next, i.e. OP_READ or OP_WRITE.

Note that if finishConnect() returns false you should just keep selecting, and if it throws an exception the connection has failed and you should close the channel.

If you want to avoid all this complication it is usually simpler to do the connect while still in blocking mode, and then put the channel into non-blocking mode and select.

Although there is really very little point in using NIO in a client at all.

See here for a fuller version of this answer.

Community
  • 1
  • 1
user207421
  • 305,947
  • 44
  • 307
  • 483
  • when i use socketChannel.register(selector, SelectionKey.OP_CONNECT); int result = selector.select(); System.out.println(result); It always return 1 whether the port is open,so when the port is closed what event is ready?why it also return 1.@EJP – firebroo Oct 20 '14 at 00:11
  • Because it wants you to call `finishConnect(),` as outlined above. So do that. Then you will either get true, false, or an exception. – user207421 Oct 20 '14 at 01:09