Unfortunately the common java.net.ServerSocket
as well as the java.nio.channels.ServerSocketChannel
only feature a blocking method to accept incoming connections. However the java.nio
package features many other classes and methods to handle I/O-Operations in a single thread by multiplexing the opened channels.
This approach would still enforce a dedicated Thread for the accepting ServerSocketChannel
but you could handle every accepted connection in a single thread.
In comparison the ServerSocket
approach needs one new thread for each new connection.
Imgaine you connect 100 clients using a ServerSocket
then you will end up with 101 thread. With a ServerSocketChannel
you could end up using only 2 thread.
Still programming is often about a tradeoff between complexity/flexibility and performance. So keep that in mind.
A possible solution I could think of could look like this:
public static void main( String[] args ) throws IOException
{
int portNr = 8080;
ExecutorService es = Executors.newSingleThreadExecutor();
ChannelHandler ch = new ChannelHandler();
es.execute( ch );
// Starting server:
ServerSocketChannel serv = ServerSocketChannel.open();
// Bind socket to Port
serv.socket().bind(new InetSocketAddress(portNr));
while( serverAlive )
{
ch.addChannel(serv.accept());
}
serv.close();
}
How you actually process the new added SocketChannel
depends on your application. And so does the ChannelHandler#addChannel
method.