This is part of NIO
Non Blocking TLS Exchange
When it came to making secure phone calls, my sister might as well have used a bullhorn. Any time she called her friends, my brother, would quietly listen to everything they said from another phone.
My sister needed a more secure connection ...
Though the NIO Socket tutorial showed you how to connect to sockets and non-blocking transmit data across channels, you might want more security in the socket connections. Transport Layer Security, TLS, (http://en.wikipedia.org/wiki/Secure_Sockets_Layer) which provides secure communications on the Internet for data transfers is represented in the LimeWire NIO via the TLSNIOSocket class.
Note: see here for the full source code.
LimeWire NIO TLS
This sample code uses a client server model for connections (TLSNIOSocket for the client and SSLServerSocket for the server). The client connects with the localhost and uses a random port, 9999.
First, you must create a Java NIO SSLContext object which is used to create the SSLServerSocketFactory. The factory then creates the SSLServerSocket.
SSLContext context = SSLContext.getInstance("TLS"); context.init(null, null, null); SSLServerSocketFactory factory = context.getServerSocketFactory(); SSLServerSocket server = (SSLServerSocket) factory.createServerSocket(9999);
In this case, you set up the server’s client authentication settings (See http://java.sun.com/j2se/1.4.2/docs/api/javax/net/ssl/SSLServerSocket.html for more information.)
server.setNeedClientAuth(false); server.setWantClientAuth(false); server.setEnabledCipherSuites(new String[] { "TLS_DH_anon_WITH_AES_128_CBC_SHA" });
Now, set up the client which connects to the server via localhost.
TLSNIOSocket socket = new TLSNIOSocket("127.0.0.1", 9999);
The server accepts the client’s connection request.
Socket accepted = server.accept();
Create a channel which is the client’s observer.
WriteBufferChannel clientOut = new WriteBufferChannel(); socket.setWriteObserver(clientOut);
The following code waits for the setting of the write channel to take place.
NIODispatcher.instance().getScheduledExecutorService().submit( new Runnable() { public void run() { } }).get();
Now you can read and write data between the sockets.
String Message = new String("This is my message."); clientOut.setBuffer(ByteBuffer.wrap(Message.toString().getBytes())); byte[] serverB = new byte[1000]; accepted.getInputStream().read(serverB); System.out.println(new String(serverB, 0, Message.length()));
When you are done, close the sockets.
socket.close(); accepted.close(); server.close();
See here for the full source code.
Return to the LimeWire NIO articles, LimeWire_NIO_Articles.


