0

I'm currently developing an asynchronous server and client communication using nio2 asynchronous channels. How can I use it asynchronous. Do I need to open up a Thread for each connection? But this is not asynchronous??

public class JavaAsyncServer {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        try {
            AsynchronousServerSocketChannel listener = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(5000));
            while(true){
            listener.accept().get();
            System.out.println("Accept");
            }
        } catch (IOException ex) {
            Logger.getLogger(JavaAsyncServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

It works well. If I connect via browser it prints accept. But how can I handle messages now?

Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82
Steinliiippp
  • 373
  • 4
  • 20
  • I should warn you that NIO2 is at least twice as complicated to implement than NIO and generally slower unless you have inifinspan. Why do you want to do this? – Peter Lawrey Feb 25 '16 at 11:25
  • I want to create an server which dont use one thread per connection. I tried it with netty but there i have the problem if i send a message back to the client, that i can only receive them in the class which is provided by netty and not everywhere in my code .... – Steinliiippp Feb 25 '16 at 11:29
  • NIO2 uses a background thread pool to send the data. It might not worth the added complexity. If you have less than 1000 threads you might be better off using blocking NIO, plain IO. – Peter Lawrey Feb 25 '16 at 11:46
  • Normaly my VM stops working at 100 Threads? How can you reach 1000 threads? – Steinliiippp Feb 26 '16 at 08:26
  • Most OSes, can handle 10,000 threads easily but you burn about 1 CPU at this point which is not efficient. The program still works, just not well. If your application stops working at 100 threads, then you have a scale-ability problem which NIO won't help you with. – Peter Lawrey Feb 26 '16 at 08:52

0 Answers0