2

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?

judepereira
  • 1,239
  • 2
  • 17
  • 24

3 Answers3

0

You can't. The question doesn't make sense. SocketChannels are plaintext. SSLContexts are for SSL.

user207421
  • 305,947
  • 44
  • 307
  • 483
0

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.

Jesper
  • 202,709
  • 46
  • 318
  • 350
0

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).

Mariano Barrios
  • 461
  • 5
  • 10