I'm looking to implement NIO for a SSL socket. However, every example that I've found, uses SocketChannel.open() to get the socket channel.
From a SSLContext, how can I get a SocketChannel?
I'm looking to implement NIO for a SSL socket. However, every example that I've found, uses SocketChannel.open() to get the socket channel.
From a SSLContext, how can I get a SocketChannel?
You can't. The question doesn't make sense. SocketChannels
are plaintext. SSLContexts
are for SSL.
This is unfortunately not very easy. You can't directly create a SocketChannel
that automatically uses SSL from an SSLContext
.
From the SSLContext
, you can create an SSLEngine
, and you'll have to call it appropriately to handle the SSL handshake. This isn't a matter of a few lines of code.
I have an sslclient example on GitHub with a class SSLSocketChannel
which shows how to do this.
Sadly, that is impossible to do with the standard Java library.
SSL/TLS is implemented in Java using SSLEngine, but that class is seriously hard to use correctly.
But there are options. TLS Channel is a simple library that does exactly that: wrapping a SSLContext (or SSLEngine) and exposing a ByteChannel interface, doing the heavy lifting internally.
(Disclaimer: I am the library's main author).