3

Java 7 shipped with asynchronous I/O. Does anyone here know if I can use this to make async calls to a SecureSocket?

Rephrased: If I am using sslContext.getSocketFactory().createSocket("127.0.0.1", 42), then using socket.getOutputStream() and socket.getInputStream() to communicate in a blocking way; what changes would I need to make to access the async functions which would allow me to re-write my code to work asynchronously?

700 Software
  • 85,281
  • 83
  • 234
  • 341

3 Answers3

5

SSL/TLS in Java with Non-blocking I/O isn't new in Java 7, but was introduced in Java SE 5. This can be done using the SSLEngine instead of sockets.

The SSLEngine is notoriously difficult to use. You can in principle convert between channels and InputStream/OutputStreams using the Channels class, but there's also quite a lot to do in terms of using the SSLEngine itself. Here are a few pointers:

Bruno
  • 119,590
  • 31
  • 270
  • 376
  • I read that async I/O is better than non blocking I/O. See the responses to [this comment](http://stackoverflow.com/questions/592303/asynchronous-io-in-java#comment12606745_592592). It is not dramatically better, but it is supposed to be better, and it is only introduced in Java 7. – 700 Software Mar 01 '13 at 01:42
  • Indeed, but even with NIO2, you'll have to use channels and the `SSLEngine`. Whether the extra complexity is worth the performance improvements, I don't know. There's a [talk by J.F. Arcand (Grizzly project)](parleys.com/d/318), but it doesn't seem to talk about SSL. – Bruno Mar 01 '13 at 10:15
2

As Bruno correctly mentions, SSLEngine is the standard way of doing asynchronous SSL. But that class is seriously hard to use.

I came across the same problem some time ago and ended up writing my own library. There are some examples out there and of course there is also the code inside projects like Netty, etc. But neither option is robust or easily reusable.

TLS Channel wraps an SSLEngine in a ByteBuffer and allows to use it just like normal SocketChannels.

Mariano Barrios
  • 461
  • 5
  • 10
1

Asynchronous IO (part of Java NIO) does not use streams but rather channels, buffers and selectors. You can definitely still connect to secure servers though. There will be a lot of changes required to your current code though, so you might not want to update to Asynch IO unless you have a very good reason.

I recommend this tutorial as a starting point.

RudolphEst
  • 1,240
  • 13
  • 21