1

What is the best way to accomplish a non blocking TCP connect in Java? I want to be able to use the socket with ordinary streams (occasionally SSL). I also have to target Android 2.1, so I can't afford the latest and the greatest.

Jörgen Sigvardsson
  • 4,839
  • 3
  • 28
  • 51
  • 1
    Use a blocking TCP connection, but place the code that manages it on a separate thread? – aroth Jan 08 '12 at 10:41
  • I am doing this, but the connect may block quite a while, depending on the networking conditions. Especially when e phone keeps switching between gsm and umts for instance. – Jörgen Sigvardsson Jan 08 '12 at 10:54

1 Answers1

2

You can use SocketChannel and configureBlocking(false). If you have more than one non-blocking I/O channel and you intend to use them all from a single thread you will probably find Selector very useful, too.

Note that it is generally easier and less error-prone to use blocking sockets and use multiple threads to make sure your app can continue doing useful work while it is blocked waiting for I/O to complete.

Adam Zalcman
  • 26,643
  • 4
  • 71
  • 92
  • +1: Totally agree. Blocking mode is the default, and you don't need to call configureBlocking to use it. NIO Was introduced in Java 1.4 in 2002 and pre-dates Android by a few years. ;) – Peter Lawrey Jan 08 '12 at 10:49
  • I have thought about using NIO, but it doesn't really work well with SSL, does it? – Jörgen Sigvardsson Jan 08 '12 at 10:55
  • There indeed seem to be issues with passing SSLSocketChannel to Selector. If you use Selector see [this question](http://stackoverflow.com/questions/867751/ssl-and-socketchannel). Unfortunately a link in the first answer seems broken. – Adam Zalcman Jan 08 '12 at 11:07