SlideShare a Scribd company logo
1 of 102
Non-Blocking IO with
           Netty


Mariano Cortesi   Fernando Zunino
@marianocortesi      @fzunino
Por que Non Blocking IO?
Por que Non Blocking IO?
Por que Non Blocking IO?
Por que Non Blocking IO?
Construyendo servidores



   Estructura básica



 Leer     Decodificar                Codificar      Enviar
                       Procesar
Request    Request                  Respuesta    Respuesta
El Camino Tradicional

     ✓ Thread por conexión
     ✓ Uso de IO bloqueante
     ✓ Modelo sencillo de programación


                              Leer   Decodificar   Procesar   Codificar   Enviar
Cliente
                             Handler


Cliente       Servidor        Leer   Decodificar   Procesar   Codificar   Enviar

                             Handler

Cliente
                              Leer   Decodificar   Procesar   Codificar   Enviar

                             Handler
An Echo Server • Java OIO




public class ThreadPoolEchoServer {

    public static void main(String[] args) throws IOException {
        ServerSocket servSock = new ServerSocket(20007);

        Executor service = Executors.newCachedThreadPool();
        while (!Thread.interrupted()) {
            Socket clntSock = servSock.accept();
            service.execute(new EchoWorker(clntSock));
        }
    }
}
An Echo Server • Java OIO




public class ThreadPoolEchoServer {                         Inicialización de socket
                                                                  para escucha
    public static void main(String[] args) throws IOException {
        ServerSocket servSock = new ServerSocket(20007);

        Executor service = Executors.newCachedThreadPool();
        while (!Thread.interrupted()) {
            Socket clntSock = servSock.accept();
            service.execute(new EchoWorker(clntSock));
        }
    }
}
An Echo Server • Java OIO




             public class ThreadPoolEchoServer {

                    public static void main(String[] args) throws IOException {
Inicialización de       ServerSocket servSock = new ServerSocket(20007);
pool de threads
                        Executor service = Executors.newCachedThreadPool();
                        while (!Thread.interrupted()) {
                            Socket clntSock = servSock.accept();
                            service.execute(new EchoWorker(clntSock));
                        }
                    }
             }
An Echo Server • Java OIO




public class ThreadPoolEchoServer {

    public static void main(String[] args) throws IOException {
        ServerSocket servSock = new ServerSocket(20007);

        Executor service = Executors.newCachedThreadPool();
        while (!Thread.interrupted()) {
                                                         Se acepta conexión
            Socket clntSock = servSock.accept();
            service.execute(new EchoWorker(clntSock));
        }
    }
}
An Echo Server • Java OIO




public class ThreadPoolEchoServer {

    public static void main(String[] args) throws IOException {
        ServerSocket servSock = new ServerSocket(20007);

        Executor service = Executors.newCachedThreadPool();
        while (!Thread.interrupted()) {
            Socket clntSock = servSock.accept();
            service.execute(new EchoWorker(clntSock));
        }
    }
                                                   Se ejecuta worker thread
}
An Echo Server • Java OIO




public class ThreadPoolEchoServer {

    public static void main(String[] args) throws IOException {
        ServerSocket servSock = new ServerSocket(20007);

        Executor service = Executors.newCachedThreadPool();
        while (!Thread.interrupted()) {
            Socket clntSock = servSock.accept();
            service.execute(new EchoWorker(clntSock));
        }
    }
}
An Echo Server • Java OIO
public class EchoWorker implements Runnable {

    public EchoWorker(final Socket s) {
        this.socket = s;
    }

    public void run() {
        try {
            InputStream in = this.socket.getInputStream();
            OutputStream out = this.socket.getOutputStream();

            int recvMsgSize;
            byte[] receiveBuf = new byte[256];

            while ((recvMsgSize = in.read(receiveBuf)) != -1) {
                out.write(receiveBuf, 0, recvMsgSize);
            }
        } catch (IOException e) { // ...
        } finally {
            try {
                this.socket.close();
            } catch (IOException e) { // ... }
        }
    }
}
An Echo Server • Java OIO
public class EchoWorker implements Runnable {

    public EchoWorker(final Socket s) {
        this.socket = s;
    }
                                                        Obtención de Streams de
    public void run() {                                     entrada y salida
        try {
            InputStream in = this.socket.getInputStream();
            OutputStream out = this.socket.getOutputStream();

            int recvMsgSize;
            byte[] receiveBuf = new byte[256];

            while ((recvMsgSize = in.read(receiveBuf)) != -1) {
                out.write(receiveBuf, 0, recvMsgSize);
            }
        } catch (IOException e) { // ...
        } finally {
            try {
                this.socket.close();
            } catch (IOException e) { // ... }
        }
    }
}
An Echo Server • Java OIO
public class EchoWorker implements Runnable {

    public EchoWorker(final Socket s) {
        this.socket = s;
    }

    public void run() {
        try {
            InputStream in = this.socket.getInputStream();
            OutputStream out = this.socket.getOutputStream();

            int recvMsgSize;                                 Se lee hasta que el
                                                         cliente cierre la conexión
            byte[] receiveBuf = new byte[256];
                                                                (bloqueante)

            while ((recvMsgSize = in.read(receiveBuf)) != -1) {
                out.write(receiveBuf, 0, recvMsgSize);
            }
        } catch (IOException e) { // ...
        } finally {
            try {
                this.socket.close();
            } catch (IOException e) { // ... }
        }
    }
}
An Echo Server • Java OIO
public class EchoWorker implements Runnable {

    public EchoWorker(final Socket s) {
        this.socket = s;
    }

    public void run() {
        try {
            InputStream in = this.socket.getInputStream();
            OutputStream out = this.socket.getOutputStream();

            int recvMsgSize;
            byte[] receiveBuf = new byte[256];

            while ((recvMsgSize = in.read(receiveBuf)) != -1) {
                out.write(receiveBuf, 0, recvMsgSize);
            }
                                                        Se reenvia lo leido al
        } catch (IOException e) { // ...                 cliente (bloqueante)
        } finally {
            try {
                this.socket.close();
            } catch (IOException e) { // ... }
        }
    }
}
An Echo Server • Java OIO
public class EchoWorker implements Runnable {

    public EchoWorker(final Socket s) {
        this.socket = s;
    }

    public void run() {
        try {
            InputStream in = this.socket.getInputStream();
            OutputStream out = this.socket.getOutputStream();

            int recvMsgSize;
            byte[] receiveBuf = new byte[256];

            while ((recvMsgSize = in.read(receiveBuf)) != -1) {
                out.write(receiveBuf, 0, recvMsgSize);
            }
        } catch (IOException e) { // ...
        } finally {
            try {
                this.socket.close();
            } catch (IOException e) { // ... } el socket
                                         Se cierra
        }
    }
}
An Echo Server • Java OIO
public class EchoWorker implements Runnable {

    public EchoWorker(final Socket s) {
        this.socket = s;
    }

    public void run() {
        try {
            InputStream in = this.socket.getInputStream();
            OutputStream out = this.socket.getOutputStream();

            int recvMsgSize;
            byte[] receiveBuf = new byte[256];

            while ((recvMsgSize = in.read(receiveBuf)) != -1) {
                out.write(receiveBuf, 0, recvMsgSize);
            }
        } catch (IOException e) { // ...
        } finally {
            try {
                this.socket.close();
            } catch (IOException e) { // ... }
        }
    }
}
El Camino Tradicional: Problemas
El Camino Tradicional: Problemas



✓ Estado compartido entre clientes
El Camino Tradicional: Problemas



✓ Estado compartido entre clientes
 ✓Sincronización
El Camino Tradicional: Problemas



✓ Estado compartido entre clientes
 ✓Sincronización
✓ Priorización de clientes
El Camino Tradicional: Problemas



✓ Estado compartido entre clientes
 ✓Sincronización
✓ Priorización de clientes
✓ Alta escala (C10K)
El Camino Tradicional: Problemas



✓ Estado compartido entre clientes
 ✓Sincronización
✓ Priorización de clientes
✓ Alta escala (C10K)
 ✓ Conexiones Persistentes
El Camino Tradicional: Problemas



✓ Estado compartido entre clientes
 ✓Sincronización
✓ Priorización de clientes
✓ Alta escala (C10K)
 ✓ Conexiones Persistentes
 ✓ Context Switching Overhead
El Camino Tradicional: Problemas



✓ Estado compartido entre clientes
 ✓Sincronización
✓ Priorización de clientes
✓ Alta escala (C10K)
 ✓ Conexiones Persistentes
 ✓ Context Switching Overhead
 ✓ Consumo de memoria
Non Blocking IO: What’s the story?


✓ Modelo orientado a eventos     Reactor Pattern
✓ Un único thread de procesamiento
✓ Uso de Readiness Notification y Non Blocking IO

                                                 Leer
        Cliente
                                               Decodificar
                                read events


                                                Procesar
        Cliente       Reactor   write events


                                                Codificar

        Cliente
                                                 Enviar
Non Blocking IO vs. Blocking IO
Non Blocking IO en Java
Non Blocking IO en Java




✓ Java NIO
Non Blocking IO en Java




✓ Java NIO
✓ Frameworks
Non Blocking IO en Java




✓ Java NIO
✓ Frameworks
 ✓ Apache Mina
Non Blocking IO en Java




✓ Java NIO
✓ Frameworks
 ✓ Apache Mina
 ✓ JBoss Netty
Non Blocking IO en Java - NIO Diseño

     Java NIO




       Dispatcher              EventHandler



                     *                    1
          Selector       SelectionKey         SelectableChannel



                                               SocketChannel
java.nio.channels
An Echo Server • Java NIO
public class Dispatcher {

    public Dispatcher(final int port, final EventHandler handler) {
         ...
    }

    public void run() throws IOException {
        Selector selector = Selector.open();

        ServerSocketChannel listenChannel = ServerSocketChannel.open();
        listenChannel.socket().bind(new InetSocketAddress(this.port));
        listenChannel.configureBlocking(false);
        listenChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (!Thread.interrupted()) {
            if (selector.select(3000) == 0) continue;

            Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
            while (keyIter.hasNext()) {
                SelectionKey key = keyIter.next();

                if (key.isAcceptable()) {
                    handler.handleAccept(key);
                }
                if (key.isReadable()) {
                    handler.handleRead(key);
                }
                if (key.isValid() && key.isWritable()) {
                    handler.handleWrite(key);
                }
                keyIter.remove(); // remove from set of selected keys
            }
        }
    }
}
An Echo Server • Java NIO
public class Dispatcher {

    public Dispatcher(final int port, final EventHandler handler) {
         ...
                                                    Crea selector para
    }
                                                     monitorear sockets
    public void run() throws IOException {          pasivos y conexiones
        Selector selector = Selector.open();

        ServerSocketChannel listenChannel = ServerSocketChannel.open();
        listenChannel.socket().bind(new InetSocketAddress(this.port));
        listenChannel.configureBlocking(false);
        listenChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (!Thread.interrupted()) {
            if (selector.select(3000) == 0) continue;

            Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
            while (keyIter.hasNext()) {
                SelectionKey key = keyIter.next();

                if (key.isAcceptable()) {
                    handler.handleAccept(key);
                }
                if (key.isReadable()) {
                    handler.handleRead(key);
                }
                if (key.isValid() && key.isWritable()) {
                    handler.handleWrite(key);
                }
                keyIter.remove(); // remove from set of selected keys
            }
        }
    }
}
An Echo Server • Java NIO
public class Dispatcher {

    public Dispatcher(final int port, final EventHandler handler) {
         ...
    }

    public void run() throws IOException {                                  Inicialización de socket
        Selector selector = Selector.open();                               para escucha en forma no
                                                                                   bloqueante
        ServerSocketChannel listenChannel = ServerSocketChannel.open();
        listenChannel.socket().bind(new InetSocketAddress(this.port));
        listenChannel.configureBlocking(false);
        listenChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (!Thread.interrupted()) {
            if (selector.select(3000) == 0) continue;

            Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
            while (keyIter.hasNext()) {
                SelectionKey key = keyIter.next();

                if (key.isAcceptable()) {
                    handler.handleAccept(key);
                }
                if (key.isReadable()) {
                    handler.handleRead(key);
                }
                if (key.isValid() && key.isWritable()) {
                    handler.handleWrite(key);
                }
                keyIter.remove(); // remove from set of selected keys
            }
        }
    }
}
An Echo Server • Java NIO
public class Dispatcher {

    public Dispatcher(final int port, final EventHandler handler) {
         ...
    }

    public void run() throws IOException {
        Selector selector = Selector.open();

        ServerSocketChannel listenChannel = ServerSocketChannel.open();
        listenChannel.socket().bind(new InetSocketAddress(this.port));
        listenChannel.configureBlocking(false);                                  Registra socket
        listenChannel.register(selector, SelectionKey.OP_ACCEPT);             declarando interés en
                                                                               nuevas conexiones
        while (!Thread.interrupted()) {
            if (selector.select(3000) == 0) continue;

            Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
            while (keyIter.hasNext()) {
                SelectionKey key = keyIter.next();

                if (key.isAcceptable()) {
                    handler.handleAccept(key);
                }
                if (key.isReadable()) {
                    handler.handleRead(key);
                }
                if (key.isValid() && key.isWritable()) {
                    handler.handleWrite(key);
                }
                keyIter.remove(); // remove from set of selected keys
            }
        }
    }
}
An Echo Server • Java NIO
           public class Dispatcher {

                   public Dispatcher(final int port, final EventHandler handler) {
                        ...
                   }

                   public void run() throws IOException {
                       Selector selector = Selector.open();

                     ServerSocketChannel listenChannel = ServerSocketChannel.open();
                     listenChannel.socket().bind(new InetSocketAddress(this.port));
Monitorea actividad en
                     listenChannel.configureBlocking(false);
  todos los sockets listenChannel.register(selector, SelectionKey.OP_ACCEPT);
     registrados
                       while (!Thread.interrupted()) {
                           if (selector.select(3000) == 0) continue;

                           Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
                           while (keyIter.hasNext()) {
                               SelectionKey key = keyIter.next();

                               if (key.isAcceptable()) {
                                   handler.handleAccept(key);
                               }
                               if (key.isReadable()) {
                                   handler.handleRead(key);
                               }
                               if (key.isValid() && key.isWritable()) {
                                   handler.handleWrite(key);
                               }
                               keyIter.remove(); // remove from set of selected keys
                           }
                       }
                   }
           }
An Echo Server • Java NIO
public class Dispatcher {

    public Dispatcher(final int port, final EventHandler handler) {
         ...
    }

    public void run() throws IOException {
        Selector selector = Selector.open();

        ServerSocketChannel listenChannel = ServerSocketChannel.open();
        listenChannel.socket().bind(new InetSocketAddress(this.port));
        listenChannel.configureBlocking(false);
        listenChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (!Thread.interrupted()) {
            if (selector.select(3000) == 0) continue;

            Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
            while (keyIter.hasNext()) {                                            Detecta y dispara eventos
                SelectionKey key = keyIter.next();                                    de acuerdo al tipo
                if (key.isAcceptable()) {
                    handler.handleAccept(key);
                }
                if (key.isReadable()) {
                    handler.handleRead(key);
                }
                if (key.isValid() && key.isWritable()) {
                    handler.handleWrite(key);
                }
                keyIter.remove(); // remove from set of selected keys
            }
        }
    }
}
An Echo Server • Java NIO
public class Dispatcher {

    public Dispatcher(final int port, final EventHandler handler) {
         ...
    }

    public void run() throws IOException {
        Selector selector = Selector.open();

        ServerSocketChannel listenChannel = ServerSocketChannel.open();
        listenChannel.socket().bind(new InetSocketAddress(this.port));
        listenChannel.configureBlocking(false);
        listenChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (!Thread.interrupted()) {
            if (selector.select(3000) == 0) continue;

            Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
            while (keyIter.hasNext()) {
                SelectionKey key = keyIter.next();

                if (key.isAcceptable()) {
                    handler.handleAccept(key);
                }
                if (key.isReadable()) {
                    handler.handleRead(key);
                }
                if (key.isValid() && key.isWritable()) {
                    handler.handleWrite(key);
                }
                keyIter.remove(); // remove from set of selected keys
            }
        }
    }
}
An Echo Server • Java NIO
public class EchoProtocolEventHandler implements EventHandler {
    private static final int BUFSIZE = 256;

    public void handleAccept(SelectionKey key) throws IOException {
        SocketChannel clntChan = ((ServerSocketChannel) key.channel()).accept();
        clntChan.configureBlocking(false);
        clntChan.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(BUFSIZE));
    }

    public void handleRead(SelectionKey key) throws IOException {
        SocketChannel clntChan = (SocketChannel) key.channel();
        ByteBuffer buf = (ByteBuffer) key.attachment();
        long bytesRead = clntChan.read(buf);
        if (bytesRead == -1) { // Did the other end close?
            clntChan.close();
        } else if (bytesRead > 0) {
            key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
        }
    }

    public void handleWrite(SelectionKey key) throws IOException {
        ByteBuffer buf = (ByteBuffer) key.attachment();
        buf.flip();
        SocketChannel clntChan = (SocketChannel) key.channel();
        clntChan.write(buf);
        if (!buf.hasRemaining()) {
            key.interestOps(SelectionKey.OP_READ);
        }
        buf.compact();
    }
}
An Echo Server • Java NIO
public class EchoProtocolEventHandler implements EventHandler {
    private static final int BUFSIZE = 256;
                                                                              Acepta nueva conexión
    public void handleAccept(SelectionKey key) throws IOException {
        SocketChannel clntChan = ((ServerSocketChannel) key.channel()).accept();
        clntChan.configureBlocking(false);
        clntChan.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(BUFSIZE));
    }

    public void handleRead(SelectionKey key) throws IOException {
        SocketChannel clntChan = (SocketChannel) key.channel();
        ByteBuffer buf = (ByteBuffer) key.attachment();
        long bytesRead = clntChan.read(buf);
        if (bytesRead == -1) { // Did the other end close?
            clntChan.close();
        } else if (bytesRead > 0) {
            key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
        }
    }

    public void handleWrite(SelectionKey key) throws IOException {
        ByteBuffer buf = (ByteBuffer) key.attachment();
        buf.flip();
        SocketChannel clntChan = (SocketChannel) key.channel();
        clntChan.write(buf);
        if (!buf.hasRemaining()) {
            key.interestOps(SelectionKey.OP_READ);
        }
        buf.compact();
    }
}
An Echo Server • Java NIO
public class EchoProtocolEventHandler implements EventHandler {
    private static final int BUFSIZE = 256;

    public void handleAccept(SelectionKey key) throws IOException {
        SocketChannel clntChan = ((ServerSocketChannel) key.channel()).accept();
        clntChan.configureBlocking(false);
        clntChan.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(BUFSIZE));
    }
                                                                             Registra nuevo socket
    public void handleRead(SelectionKey key) throws IOException {            declarando interés en
        SocketChannel clntChan = (SocketChannel) key.channel();              lectura y asocia buffer
        ByteBuffer buf = (ByteBuffer) key.attachment();
        long bytesRead = clntChan.read(buf);
        if (bytesRead == -1) { // Did the other end close?
            clntChan.close();
        } else if (bytesRead > 0) {
            key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
        }
    }

    public void handleWrite(SelectionKey key) throws IOException {
        ByteBuffer buf = (ByteBuffer) key.attachment();
        buf.flip();
        SocketChannel clntChan = (SocketChannel) key.channel();
        clntChan.write(buf);
        if (!buf.hasRemaining()) {
            key.interestOps(SelectionKey.OP_READ);
        }
        buf.compact();
    }
}
An Echo Server • Java NIO
public class EchoProtocolEventHandler implements EventHandler {
    private static final int BUFSIZE = 256;

    public void handleAccept(SelectionKey key) throws IOException {
        SocketChannel clntChan = ((ServerSocketChannel) key.channel()).accept();
        clntChan.configureBlocking(false);
        clntChan.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(BUFSIZE));
    }

    public void handleRead(SelectionKey key) throws IOException {
        SocketChannel clntChan = (SocketChannel) key.channel();
        ByteBuffer buf = (ByteBuffer) key.attachment();
        long bytesRead = clntChan.read(buf);                                 Lee datos en buffer
        if (bytesRead == -1) { // Did the other end close?                        asociado
            clntChan.close();
        } else if (bytesRead > 0) {
            key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
        }
    }

    public void handleWrite(SelectionKey key) throws IOException {
        ByteBuffer buf = (ByteBuffer) key.attachment();
        buf.flip();
        SocketChannel clntChan = (SocketChannel) key.channel();
        clntChan.write(buf);
        if (!buf.hasRemaining()) {
            key.interestOps(SelectionKey.OP_READ);
        }
        buf.compact();
    }
}
An Echo Server • Java NIO
public class EchoProtocolEventHandler implements EventHandler {
    private static final int BUFSIZE = 256;

    public void handleAccept(SelectionKey key) throws IOException {
        SocketChannel clntChan = ((ServerSocketChannel) key.channel()).accept();
        clntChan.configureBlocking(false);
        clntChan.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(BUFSIZE));
    }

    public void handleRead(SelectionKey key) throws IOException {
        SocketChannel clntChan = (SocketChannel) key.channel();
        ByteBuffer buf = (ByteBuffer) key.attachment();
        long bytesRead = clntChan.read(buf);
        if (bytesRead == -1) { // Did the other end close?
            clntChan.close();
        } else if (bytesRead > 0) {
            key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);   Detecta fin de conexión
        }
    }

    public void handleWrite(SelectionKey key) throws IOException {
        ByteBuffer buf = (ByteBuffer) key.attachment();
        buf.flip();
        SocketChannel clntChan = (SocketChannel) key.channel();
        clntChan.write(buf);
        if (!buf.hasRemaining()) {
            key.interestOps(SelectionKey.OP_READ);
        }
        buf.compact();
    }
}
An Echo Server • Java NIO
public class EchoProtocolEventHandler implements EventHandler {
    private static final int BUFSIZE = 256;

    public void handleAccept(SelectionKey key) throws IOException {
        SocketChannel clntChan = ((ServerSocketChannel) key.channel()).accept();
        clntChan.configureBlocking(false);
        clntChan.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(BUFSIZE));
    }

    public void handleRead(SelectionKey key) throws IOException {
        SocketChannel clntChan = (SocketChannel) key.channel();
        ByteBuffer buf = (ByteBuffer) key.attachment();
        long bytesRead = clntChan.read(buf);
        if (bytesRead == -1) { // Did the other end close?
            clntChan.close();
        } else if (bytesRead > 0) {
            key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
        }
    }
                                                                                Declara interés en
    public void handleWrite(SelectionKey key) throws IOException {            escritura si hay datos a
        ByteBuffer buf = (ByteBuffer) key.attachment();                               escribir
        buf.flip();
        SocketChannel clntChan = (SocketChannel) key.channel();
        clntChan.write(buf);
        if (!buf.hasRemaining()) {
            key.interestOps(SelectionKey.OP_READ);
        }
        buf.compact();
    }
}
An Echo Server • Java NIO
public class EchoProtocolEventHandler implements EventHandler {
    private static final int BUFSIZE = 256;

    public void handleAccept(SelectionKey key) throws IOException {
        SocketChannel clntChan = ((ServerSocketChannel) key.channel()).accept();
        clntChan.configureBlocking(false);
        clntChan.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(BUFSIZE));
    }

    public void handleRead(SelectionKey key) throws IOException {
        SocketChannel clntChan = (SocketChannel) key.channel();
        ByteBuffer buf = (ByteBuffer) key.attachment();
        long bytesRead = clntChan.read(buf);
        if (bytesRead == -1) { // Did the other end close?
            clntChan.close();
        } else if (bytesRead > 0) {
            key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
        }
    }

    public void handleWrite(SelectionKey key) throws IOException {
        ByteBuffer buf = (ByteBuffer) key.attachment();
        buf.flip();
        SocketChannel clntChan = (SocketChannel) key.channel();
        clntChan.write(buf);                                                  Envia datos al socket
        if (!buf.hasRemaining()) {
            key.interestOps(SelectionKey.OP_READ);
        }
        buf.compact();
    }
}
An Echo Server • Java NIO
public class EchoProtocolEventHandler implements EventHandler {
    private static final int BUFSIZE = 256;

    public void handleAccept(SelectionKey key) throws IOException {
        SocketChannel clntChan = ((ServerSocketChannel) key.channel()).accept();
        clntChan.configureBlocking(false);
        clntChan.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(BUFSIZE));
    }

    public void handleRead(SelectionKey key) throws IOException {
        SocketChannel clntChan = (SocketChannel) key.channel();
        ByteBuffer buf = (ByteBuffer) key.attachment();
        long bytesRead = clntChan.read(buf);
        if (bytesRead == -1) { // Did the other end close?
            clntChan.close();
        } else if (bytesRead > 0) {
            key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
        }
    }

    public void handleWrite(SelectionKey key) throws IOException {
        ByteBuffer buf = (ByteBuffer) key.attachment();
        buf.flip();
        SocketChannel clntChan = (SocketChannel) key.channel();
        clntChan.write(buf);
        if (!buf.hasRemaining()) {
            key.interestOps(SelectionKey.OP_READ);
        }                                               Revoca interés en escritura
        buf.compact();                                  si no hay nada para escribir
    }
}
An Echo Server • Java NIO
public class EchoProtocolEventHandler implements EventHandler {
    private static final int BUFSIZE = 256;

    public void handleAccept(SelectionKey key) throws IOException {
        SocketChannel clntChan = ((ServerSocketChannel) key.channel()).accept();
        clntChan.configureBlocking(false);
        clntChan.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(BUFSIZE));
    }

    public void handleRead(SelectionKey key) throws IOException {
        SocketChannel clntChan = (SocketChannel) key.channel();
        ByteBuffer buf = (ByteBuffer) key.attachment();
        long bytesRead = clntChan.read(buf);
        if (bytesRead == -1) { // Did the other end close?
            clntChan.close();
        } else if (bytesRead > 0) {
            key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
        }
    }

    public void handleWrite(SelectionKey key) throws IOException {
        ByteBuffer buf = (ByteBuffer) key.attachment();
        buf.flip();
        SocketChannel clntChan = (SocketChannel) key.channel();
        clntChan.write(buf);
        if (!buf.hasRemaining()) {
            key.interestOps(SelectionKey.OP_READ);
        }
        buf.compact();
    }
}
An Echo Server • Java NIO


public interface EventHandler {
      void handleAccept(SelectionKey key) throws IOException;
      void handleRead(SelectionKey key) throws IOException;
      void handleWrite(SelectionKey key) throws IOException;
}




public class NIOEchoServer {
    public static void main(String[] args) throws IOException {
        Dispatcher dispatcher = new Dispatcher(20007,
                                          new EchoProtocolEventHandler());
        dispatcher.run();
    }
}
Netty!!




                  from Netty Homepage

 The Netty project is an effort to provide an
asynchronous event-driven network application
framework and tools for rapid development of
maintainable high performance & high scalability
          protocol servers & clients
Netty!!




                  from Netty Homepage

 The Netty project is an effort to provide an
asynchronous event-driven network application
framework and tools for rapid development of
maintainable high performance & high scalability
  protocol servers & clients
Netty!!




                       from Netty Homepage

      The Netty project is an effort to provide an
asynchronous event-driven application
                    network
     framework and tools for rapid development of
     maintainable high performance & high scalability
               protocol servers & clients
Netty!!




                 from Netty Homepage

 The Netty project is an effort to provide an
asynchronous event-driven network application
framework and tools for rapid development of
  high performance & high scalability
maintainable
          protocol servers & clients
Netty!!




                  from Netty Homepage

 The Netty project is an effort to provide an
asynchronous event-driven network application
                    rapid development
framework and tools for           of
maintainable high performance & high scalability
          protocol servers & clients
Netty!!




                   from Netty Homepage

  The Netty project is an effort to provide an
 asynchronous event-driven network application
 framework and tools for rapid development of
 maintainable high performance & high scalability
           protocol servers & clients


Warning! Netty no es un WebServer
Netty Model • Channels

                           creates                                    handles
ChannelFactory                                    Channel                       ChannelPipeline
                                    es   with
                           &   writ                   generates                        is sorted list of
                       s
                  read


                                                                      handles

ChannelBuffer                                   ChannelEvent                    ChannelHandler


 ✓ Representa a una conexion P2P (point to point)
 ✓ Abstrae UDP / TCP
 ✓ Abstrae NIO / OIO
 ✓ API interacción conexión (abrir, cerrar, escribir, leer)
Netty Model • ChannelBuffers

                          creates                                handles
ChannelFactory                                   Channel                   ChannelPipeline
                                   es   with
                          &   writ                   generates                    is sorted list of
                      s
                 read


                                                                 handles

ChannelBuffer                                  ChannelEvent                ChannelHandler
Netty Model • ChannelBuffers

                          creates                                handles
ChannelFactory                                   Channel                   ChannelPipeline
                                   es   with
                          &   writ                   generates                    is sorted list of
                      s
                 read


                                                                 handles

ChannelBuffer                                  ChannelEvent                ChannelHandler


 ✓ Abstrae de NIO Buffers & byte arrays
 ✓ API simplificada respecto NIO Buffers
 ✓ Toda lectura y escritura se hace con ellos
Netty Model • ChannelFactory

                          creates                                handles
ChannelFactory                                   Channel                   ChannelPipeline
                                   es   with
                          &   writ                   generates                    is sorted list of
                      s
                 read


                                                                 handles

ChannelBuffer                                  ChannelEvent                ChannelHandler
Netty Model • ChannelFactory

                          creates                                handles
ChannelFactory                                   Channel                   ChannelPipeline
                                   es   with
                          &   writ                   generates                    is sorted list of
                      s
                 read


                                                                 handles

ChannelBuffer                                  ChannelEvent                ChannelHandler


 ✓ Crear Channels
 ✓ ChannelFactory impl. para UDP / TCP y OIO / NIO
 ✓ Non Blocking con: NioServerSocketChannelFactory
Netty Model • ChannelEvent

                          creates                                handles
ChannelFactory                                   Channel                   ChannelPipeline
                                   es   with
                          &   writ                   generates                    is sorted list of
                      s
                 read


                                                                 handles

ChannelBuffer                                  ChannelEvent                ChannelHandler
Netty Model • ChannelEvent

                          creates                                handles
ChannelFactory                                   Channel                   ChannelPipeline
                                   es   with
                          &   writ                   generates                    is sorted list of
                      s
                 read


                                                                 handles

ChannelBuffer                                  ChannelEvent                ChannelHandler


 ✓ Representa un evento I/O asociado a un Channel
 ✓ Puede ser upstream (entrada) or downstream (salida)
 ✓ Se pueden crear eventos custom
 ✓ Algunos tipos de evento:
   ★   messageReceived
   ★   channelOpen
   ★   channelClosed
   ★   write
Netty Model • ChannelPipeline

                          creates                                handles
ChannelFactory                                   Channel                   ChannelPipeline
                                   es   with
                          &   writ                   generates                    is sorted list of
                      s
                 read


                                                                 handles

ChannelBuffer                                  ChannelEvent                ChannelHandler
Netty Model • ChannelPipeline

                          creates                                handles
ChannelFactory                                   Channel                   ChannelPipeline
                                   es   with
                          &   writ                   generates                    is sorted list of
                      s
                 read


                                                                 handles

ChannelBuffer                                  ChannelEvent                ChannelHandler


 ✓ Asociado a un Channel
 ✓ Atrapa y Handlea los ChannelEvents
 ✓ Implementa el patron Intercepting Filter
Netty Model • ChannelHandler

                          creates                                handles
ChannelFactory                                   Channel                   ChannelPipeline
                                   es   with
                          &   writ                   generates                    is sorted list of
                      s
                 read


                                                                 handles

ChannelBuffer                                  ChannelEvent                ChannelHandler
Netty Model • ChannelHandler

                               creates                                      handles
   ChannelFactory                                     Channel                               ChannelPipeline
                                        es   with
                               &   writ                   generates                                 is sorted list of
                           s
                      read


                                                                                handles

    ChannelBuffer                                   ChannelEvent                            ChannelHandler


     ✓ Building block de un ChannelPipeline
     ✓ Handlea ChannelEvents (upstream y/o downstream)
     ✓ Decide sobre el forwarding de eventos a sus pares
upstream
            Handler



                               Handler




                                                                      Handler



                                                                                          Handler
  event
                                                                       N -1
             First




                                                                                           Last
                                2nd




                                                                                                    downstream
                                                                                                       event
An Echo Server • Netty NIO

                                              Main Class

public class EchoServer {

      public static void main(String[] args) throws Exception {
          // Configure the server.
          ServerBootstrap bootstrap = new ServerBootstrap(
                  new NioServerSocketChannelFactory(
                          Executors.newCachedThreadPool(),
                          Executors.newCachedThreadPool()));

            // Set up the pipeline factory.
            bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
                public ChannelPipeline getPipeline() throws Exception {
                    return Channels.pipeline(new EchoServerHandler());
                }
            });

            // Bind and start to accept incoming connections.
            bootstrap.bind(new InetSocketAddress(8080));
      }
}



    Ejemplo en: http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/echo/package-summary.html
An Echo Server • Netty NIO

                                              Main Class

public class EchoServer {
                                                                 Utility Class para
      public static void main(String[] args) throws Exception {inicializar un Server
          // Configure the server.
          ServerBootstrap bootstrap = new ServerBootstrap(
                  new NioServerSocketChannelFactory(
                          Executors.newCachedThreadPool(),
                          Executors.newCachedThreadPool()));

            // Set up the pipeline factory.
            bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
                public ChannelPipeline getPipeline() throws Exception {
                    return Channels.pipeline(new EchoServerHandler());
                }
            });

            // Bind and start to accept incoming connections.
            bootstrap.bind(new InetSocketAddress(8080));
      }
}



    Ejemplo en: http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/echo/package-summary.html
An Echo Server • Netty NIO

                                              Main Class

public class EchoServer {

      public static void main(String[] args) throws Exception {
          // Configure the server.
          ServerBootstrap bootstrap = new ServerBootstrap(
                                                                                              ChannelFactory para Tcp
                  new NioServerSocketChannelFactory(
                                                                                                     w/ NIO
                          Executors.newCachedThreadPool(),
                          Executors.newCachedThreadPool()));

            // Set up the pipeline factory.
            bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
                public ChannelPipeline getPipeline() throws Exception {
                    return Channels.pipeline(new EchoServerHandler());
                }
            });

            // Bind and start to accept incoming connections.
            bootstrap.bind(new InetSocketAddress(8080));
      }
}



    Ejemplo en: http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/echo/package-summary.html
An Echo Server • Netty NIO

                                              Main Class

public class EchoServer {

      public static void main(String[] args) throws Exception {
          // Configure the server.
         Boss pool thread
          ServerBootstrap bootstrap = new ServerBootstrap(
                      new NioServerSocketChannelFactory(
                              Executors.newCachedThreadPool(),
                              Executors.newCachedThreadPool()));
                                                                                      Workers pool thread
            // Set up the pipeline factory.
            bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
                public ChannelPipeline getPipeline() throws Exception {
                    return Channels.pipeline(new EchoServerHandler());
                }
            });

            // Bind and start to accept incoming connections.
            bootstrap.bind(new InetSocketAddress(8080));
      }
}



    Ejemplo en: http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/echo/package-summary.html
An Echo Server • Netty NIO

                                                         Main Class

           public class EchoServer {

                 public static void main(String[] args) throws Exception {
                     // Configure the server.
                     ServerBootstrap bootstrap = new ServerBootstrap(
                             new NioServerSocketChannelFactory(
                                     Executors.newCachedThreadPool(),
                                     Executors.newCachedThreadPool()));

                        // Set up the pipeline factory.
                        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
                            public ChannelPipeline getPipeline() throws Exception {
 ChannelPipelineFactory
para cada nuevo Channel         return Channels.pipeline(new EchoServerHandler());
       establcido           }
                        });

                       // Bind and start to accept incoming connections.
                       bootstrap.bind(new InetSocketAddress(8080));
                 }
           }



               Ejemplo en: http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/echo/package-summary.html
An Echo Server • Netty NIO

                                              Main Class

public class EchoServer {

      public static void main(String[] args) throws Exception {
          // Configure the server.
          ServerBootstrap bootstrap = new ServerBootstrap(
                  new NioServerSocketChannelFactory(
                          Executors.newCachedThreadPool(),
                          Executors.newCachedThreadPool()));

            // Set up the pipeline factory.
            bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
                public ChannelPipeline getPipeline() throws Exception {
                    return Channels.pipeline(new EchoServerHandler());
                }
            });
                                                                    Un solo handler. El echo
                                                                           Handler
            // Bind and start to accept incoming connections.
            bootstrap.bind(new InetSocketAddress(8080));
      }
}



    Ejemplo en: http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/echo/package-summary.html
An Echo Server • Netty NIO

                                              Main Class

public class EchoServer {

      public static void main(String[] args) throws Exception {
          // Configure the server.
          ServerBootstrap bootstrap = new ServerBootstrap(
                  new NioServerSocketChannelFactory(
                          Executors.newCachedThreadPool(),
                          Executors.newCachedThreadPool()));

            // Set up the pipeline factory.
            bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
                public ChannelPipeline getPipeline() throws Exception {
                    return Channels.pipeline(new EchoServerHandler());
                }
            });

            // Bind and start to accept incoming connections.
            bootstrap.bind(new InetSocketAddress(8080));
      }
}                                                                         Finalmente inicializamos
                                                                                el servidor


    Ejemplo en: http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/echo/package-summary.html
An Echo Server • Netty NIO

                                                   Handler



public class EchoServerHandler extends SimpleChannelHandler {

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
        e.getChannel().write(e.getMessage());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
        e.getCause().printStackTrace();

           Channel ch = e.getChannel();
           ch.close();
    }
}




        Ejemplo en: http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/echo/package-summary.html
An Echo Server • Netty NIO

                                                   Handler


                                                                                               Utility class para handlear
public class EchoServerHandler extends SimpleChannelHandler {                                        eventos típicos

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
        e.getChannel().write(e.getMessage());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
        e.getCause().printStackTrace();

           Channel ch = e.getChannel();
           ch.close();
    }
}




        Ejemplo en: http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/echo/package-summary.html
An Echo Server • Netty NIO

                                                      Handler



   public class EchoServerHandler extends SimpleChannelHandler {

        @Override
Event Handler para
        public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
  nuevo mensaje
              e.getChannel().write(e.getMessage());
        }

         @Override
Event Handler para void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
         public
   excepciones
               e.getCause().printStackTrace();

              Channel ch = e.getChannel();
              ch.close();
       }
   }




           Ejemplo en: http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/echo/package-summary.html
An Echo Server • Netty NIO

                                                   Handler



public class EchoServerHandler extends SimpleChannelHandler {

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
        e.getChannel().write(e.getMessage());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
        e.getCause().printStackTrace();
                                                                                        Contexto del Canal
           Channel ch = e.getChannel();                                              Permite interactuar con su
           ch.close();                                                                        pipeline
    }
}




        Ejemplo en: http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/echo/package-summary.html
An Echo Server • Netty NIO

                                                   Handler



public class EchoServerHandler extends SimpleChannelHandler {

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
        e.getChannel().write(e.getMessage());
    }                                             Interacción con el Channel:
                                                      Lectura y Escritura
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
        e.getCause().printStackTrace();

           Channel ch = e.getChannel();
           ch.close();
    }
}




        Ejemplo en: http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/echo/package-summary.html
An Echo Server • Netty OIO

                             Vuelta a OIO!

public class EchoServer {

    public static void main(String[] args) throws Exception {
        // Configure the server.
        ServerBootstrap bootstrap = new ServerBootstrap(
                new OioServerSocketChannelFactory(
                        Executors.newCachedThreadPool(),
                        Executors.newCachedThreadPool()));

        // Set up the pipeline factory.
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() throws Exception {
                return Channels.pipeline(new EchoServerHandler());
            }
        });

        // Bind and start to accept incoming connections.
        bootstrap.bind(new InetSocketAddress(8080));
    }
}
An Echo Server • Netty OIO

                             Vuelta a OIO!

public class EchoServer {

    public static void main(String[] args) throws Exception {
        // Configure the server.
        ServerBootstrap bootstrap = new ServerBootstrap(
                                                                ChannelFactory para Tcp
                new OioServerSocketChannelFactory(
                                                                       w/ OIO
                        Executors.newCachedThreadPool(),
                        Executors.newCachedThreadPool()));

        // Set up the pipeline factory.
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() throws Exception {
                return Channels.pipeline(new EchoServerHandler());
            }
        });

        // Bind and start to accept incoming connections.
        bootstrap.bind(new InetSocketAddress(8080));
    }
}
A Distributed Logger • Diseño




Protocolo
✓ Formato textual, de linea
✓ Paquete tamaño variable
✓ Mensaje por fin de linea
✓ Formato: “${level} - ${mensaje}”
            DEBUG - Algo esta mal!!
Framer Handler




Decoder Handler
                  pipeline




 LoggerPrinter
   Handler
                             A Distributed Logger • Diseño
Framer Handler




Decoder Handler




 LoggerPrinter
   Handler
                  A Distributed Logger • Framer
A Distributed Logger • Framer




                                     Decoder Handler
                   Framer Handler




                                                       LoggerPrinter
                                                         Handler
                                    Framer


import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder;
import org.jboss.netty.handler.codec.frame.Delimiters;

public class LoggerFramerHandler extends DelimiterBasedFrameDecoder {

    public LoggerFramerHandler() {
        super(8000, Delimiters.lineDelimiter());
    }
}
A Distributed Logger • Framer




                                     Decoder Handler
                   Framer Handler




                                                       LoggerPrinter
                                                         Handler
                                    Framer


import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder;
import org.jboss.netty.handler.codec.frame.Delimiters;

public class LoggerFramerHandler extends DelimiterBasedFrameDecoder {

    public LoggerFramerHandler() {                                     Framer para demarcar
        super(8000, Delimiters.lineDelimiter());                       paquetes a través de un
    }                                                                       delimitador
}
A Distributed Logger • Framer




                                     Decoder Handler
                   Framer Handler




                                                                 LoggerPrinter
                                                                   Handler
                                    Framer


import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder;
import org.jboss.netty.handler.codec.frame.Delimiters;

public class LoggerFramerHandler extends DelimiterBasedFrameDecoder {

    public LoggerFramerHandler() {
        super(8000, Delimiters.lineDelimiter());
    }
}                                                      Delimitador para lineas
Framer Handler




Decoder Handler




 LoggerPrinter
   Handler
                  A Distributed Logger • Framer
Framer Handler




Decoder Handler




 LoggerPrinter
   Handler
                  A Distributed Logger • Decoder
A Distributed Logger • Decoder




                                       Decoder Handler
                    Framer Handler




                                                         LoggerPrinter
                                                           Handler
                                      Decoder


@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
   Charset ch = Charset.defaultCharset();
   String msg = ((ChannelBuffer) e.getMessage()).toString(ch);
   String[] args = msg.split("-", 2);

    LogEvent logEvent = new LogEvent(Level.valueOf(args[0].trim()),
                                     args[1].trim());
    Channels.fireMessageReceived(ctx, logEvent);
}
A Distributed Logger • Decoder




                                       Decoder Handler
                    Framer Handler




                                                         LoggerPrinter
                                                           Handler
                                      Decoder


@Override                                              El framer deja un
public void messageReceived(ChannelHandlerContext ctx, MessageEventmsg {
                                                    ChannelBuffer como e)
   Charset ch = Charset.defaultCharset();
   String msg = ((ChannelBuffer) e.getMessage()).toString(ch);
   String[] args = msg.split("-", 2);

    LogEvent logEvent = new LogEvent(Level.valueOf(args[0].trim()),
                                     args[1].trim());
    Channels.fireMessageReceived(ctx, logEvent);
}
A Distributed Logger • Decoder




                                        Decoder Handler
                     Framer Handler




                                                          LoggerPrinter
                                                            Handler
                                       Decoder


@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
   Charset ch = Charset.defaultCharset();
   String msg = ((ChannelBuffer) e.getMessage()).toString(ch);
   String[] args = msg.split("-", 2);                               parseo y creación de un
                                                                           LogEvent

    LogEvent logEvent = new LogEvent(Level.valueOf(args[0].trim()),
                                     args[1].trim());
    Channels.fireMessageReceived(ctx, logEvent);
}
A Distributed Logger • Decoder




                                       Decoder Handler
                    Framer Handler




                                                            LoggerPrinter
                                                              Handler
                                      Decoder


@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
   Charset ch = Charset.defaultCharset();
   String msg = ((ChannelBuffer) e.getMessage()).toString(ch);
   String[] args = msg.split("-", 2);

    LogEvent logEvent = new LogEvent(Level.valueOf(args[0].trim()),
                                     args[1].trim());
    Channels.fireMessageReceived(ctx, logEvent);
}
                                                         propago el mensaje, como
                                                                LogEvent
Framer Handler




Decoder Handler




 LoggerPrinter
   Handler
                  A Distributed Logger • Decoder
Framer Handler




Decoder Handler




 LoggerPrinter
   Handler
                  A Distributed Logger • Printer
A Distributed Logger • Printer




                                    Decoder Handler
                   Framer Handler




                                                      LoggerPrinter
                                                        Handler
                                    Printer




@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
   LogEvent logEvent = (LogEvent) e.getMessage();
   System.out.println(logEvent);
}
A Distributed Logger • Printer




                                    Decoder Handler
                   Framer Handler




                                                      LoggerPrinter
                                                        Handler
                                    Printer




                                                              El msg ahora es un
@Override                                                         LogEvent
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
   LogEvent logEvent = (LogEvent) e.getMessage();
   System.out.println(logEvent);
}
A Distributed Logger • Printer




                                    Decoder Handler
                   Framer Handler




                                                      LoggerPrinter
                                                        Handler
                                    Printer




@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
   LogEvent logEvent = (LogEvent) e.getMessage();
   System.out.println(logEvent);
}
Conclusiones



✓ Non-Blocking IO
   ✓ Importa!
   ✓ Aplicaciones altamente concurrentes
     (c10k)
✓ Netty
   ✓ java nio made easy
   ✓ modelo flexible para crear servidores
     NIO (o OIO)
¿¿ Preguntas ??



We are hiring!         Apply at jobs@zaubersoftware.com

More Related Content

What's hot

Advanced Reflection in Java
Advanced Reflection in JavaAdvanced Reflection in Java
Advanced Reflection in Javakim.mens
 
HOW AND WHY GRAALVM IS QUICKLY BECOMING RELEVANT FOR YOU
HOW AND WHY GRAALVM IS QUICKLY BECOMING RELEVANT FOR YOUHOW AND WHY GRAALVM IS QUICKLY BECOMING RELEVANT FOR YOU
HOW AND WHY GRAALVM IS QUICKLY BECOMING RELEVANT FOR YOULucas Jellema
 
LatJUG. Java Bytecode Fundamentals
LatJUG. Java Bytecode FundamentalsLatJUG. Java Bytecode Fundamentals
LatJUG. Java Bytecode Fundamentalsdenis Udod
 
Nest.js Introduction
Nest.js IntroductionNest.js Introduction
Nest.js IntroductionTakuya Tejima
 
Loom Virtual Threads in the JDK 19
Loom Virtual Threads in the JDK 19Loom Virtual Threads in the JDK 19
Loom Virtual Threads in the JDK 19José Paumard
 
Spring boot Under Da Hood
Spring boot Under Da HoodSpring boot Under Da Hood
Spring boot Under Da HoodMichel Schudel
 
Practical non blocking microservices in java 8
Practical non blocking microservices in java 8Practical non blocking microservices in java 8
Practical non blocking microservices in java 8Michal Balinski
 
Hexagonal architecture with Spring Boot
Hexagonal architecture with Spring BootHexagonal architecture with Spring Boot
Hexagonal architecture with Spring BootMikalai Alimenkou
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootJosué Neis
 
Java troubleshooting thread dump
Java troubleshooting thread dumpJava troubleshooting thread dump
Java troubleshooting thread dumpejlp12
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node jsAkshay Mathur
 
Graal and Truffle: One VM to Rule Them All
Graal and Truffle: One VM to Rule Them AllGraal and Truffle: One VM to Rule Them All
Graal and Truffle: One VM to Rule Them AllThomas Wuerthinger
 
JVM @ Taobao - QCon Hangzhou 2011
JVM @ Taobao - QCon Hangzhou 2011JVM @ Taobao - QCon Hangzhou 2011
JVM @ Taobao - QCon Hangzhou 2011Kris Mok
 
Solid NodeJS with TypeScript, Jest & NestJS
Solid NodeJS with TypeScript, Jest & NestJSSolid NodeJS with TypeScript, Jest & NestJS
Solid NodeJS with TypeScript, Jest & NestJSRafael Casuso Romate
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Edureka!
 

What's hot (20)

Advanced Reflection in Java
Advanced Reflection in JavaAdvanced Reflection in Java
Advanced Reflection in Java
 
HOW AND WHY GRAALVM IS QUICKLY BECOMING RELEVANT FOR YOU
HOW AND WHY GRAALVM IS QUICKLY BECOMING RELEVANT FOR YOUHOW AND WHY GRAALVM IS QUICKLY BECOMING RELEVANT FOR YOU
HOW AND WHY GRAALVM IS QUICKLY BECOMING RELEVANT FOR YOU
 
LatJUG. Java Bytecode Fundamentals
LatJUG. Java Bytecode FundamentalsLatJUG. Java Bytecode Fundamentals
LatJUG. Java Bytecode Fundamentals
 
Nest.js Introduction
Nest.js IntroductionNest.js Introduction
Nest.js Introduction
 
Loom Virtual Threads in the JDK 19
Loom Virtual Threads in the JDK 19Loom Virtual Threads in the JDK 19
Loom Virtual Threads in the JDK 19
 
NestJS
NestJSNestJS
NestJS
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Spring boot Under Da Hood
Spring boot Under Da HoodSpring boot Under Da Hood
Spring boot Under Da Hood
 
Practical non blocking microservices in java 8
Practical non blocking microservices in java 8Practical non blocking microservices in java 8
Practical non blocking microservices in java 8
 
Hexagonal architecture with Spring Boot
Hexagonal architecture with Spring BootHexagonal architecture with Spring Boot
Hexagonal architecture with Spring Boot
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Java troubleshooting thread dump
Java troubleshooting thread dumpJava troubleshooting thread dump
Java troubleshooting thread dump
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
.Net Core
.Net Core.Net Core
.Net Core
 
Graal and Truffle: One VM to Rule Them All
Graal and Truffle: One VM to Rule Them AllGraal and Truffle: One VM to Rule Them All
Graal and Truffle: One VM to Rule Them All
 
JVM @ Taobao - QCon Hangzhou 2011
JVM @ Taobao - QCon Hangzhou 2011JVM @ Taobao - QCon Hangzhou 2011
JVM @ Taobao - QCon Hangzhou 2011
 
Solid NodeJS with TypeScript, Jest & NestJS
Solid NodeJS with TypeScript, Jest & NestJSSolid NodeJS with TypeScript, Jest & NestJS
Solid NodeJS with TypeScript, Jest & NestJS
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
 

Similar to Non blocking io with netty

Easy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVEEasy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVEUehara Junji
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsCarol McDonald
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsAzul Systems, Inc.
 
Playing With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.jsPlaying With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.jsMike Hagedorn
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Víctor Bolinches
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join frameworkMinh Tran
 
forwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docxforwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docxbudbarber38650
 
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?Julian Robichaux
 
DEV-1550: Why Java 8? Or, What's a Lambda? – IBM Connect 2017
DEV-1550: Why Java 8? Or, What's a Lambda? – IBM Connect 2017DEV-1550: Why Java 8? Or, What's a Lambda? – IBM Connect 2017
DEV-1550: Why Java 8? Or, What's a Lambda? – IBM Connect 2017panagenda
 
Closures for Java
Closures for JavaClosures for Java
Closures for Javanextlib
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?Doug Hawkins
 

Similar to Non blocking io with netty (20)

Network
NetworkNetwork
Network
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
Current State of Coroutines
Current State of CoroutinesCurrent State of Coroutines
Current State of Coroutines
 
Easy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVEEasy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVE
 
Server1
Server1Server1
Server1
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Playing With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.jsPlaying With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.js
 
Exploring Kotlin
Exploring KotlinExploring Kotlin
Exploring Kotlin
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join framework
 
forwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docxforwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docx
 
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?
 
DEV-1550: Why Java 8? Or, What's a Lambda? – IBM Connect 2017
DEV-1550: Why Java 8? Or, What's a Lambda? – IBM Connect 2017DEV-1550: Why Java 8? Or, What's a Lambda? – IBM Connect 2017
DEV-1550: Why Java 8? Or, What's a Lambda? – IBM Connect 2017
 
Closures for Java
Closures for JavaClosures for Java
Closures for Java
 
Tdd iPhone For Dummies
Tdd iPhone For DummiesTdd iPhone For Dummies
Tdd iPhone For Dummies
 
分散式系統
分散式系統分散式系統
分散式系統
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 

Recently uploaded

Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 

Recently uploaded (20)

Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 

Non blocking io with netty

  • 1. Non-Blocking IO with Netty Mariano Cortesi Fernando Zunino @marianocortesi @fzunino
  • 2. Por que Non Blocking IO?
  • 3. Por que Non Blocking IO?
  • 4. Por que Non Blocking IO?
  • 5. Por que Non Blocking IO?
  • 6. Construyendo servidores Estructura básica Leer Decodificar Codificar Enviar Procesar Request Request Respuesta Respuesta
  • 7. El Camino Tradicional ✓ Thread por conexión ✓ Uso de IO bloqueante ✓ Modelo sencillo de programación Leer Decodificar Procesar Codificar Enviar Cliente Handler Cliente Servidor Leer Decodificar Procesar Codificar Enviar Handler Cliente Leer Decodificar Procesar Codificar Enviar Handler
  • 8. An Echo Server • Java OIO public class ThreadPoolEchoServer { public static void main(String[] args) throws IOException { ServerSocket servSock = new ServerSocket(20007); Executor service = Executors.newCachedThreadPool(); while (!Thread.interrupted()) { Socket clntSock = servSock.accept(); service.execute(new EchoWorker(clntSock)); } } }
  • 9. An Echo Server • Java OIO public class ThreadPoolEchoServer { Inicialización de socket para escucha public static void main(String[] args) throws IOException { ServerSocket servSock = new ServerSocket(20007); Executor service = Executors.newCachedThreadPool(); while (!Thread.interrupted()) { Socket clntSock = servSock.accept(); service.execute(new EchoWorker(clntSock)); } } }
  • 10. An Echo Server • Java OIO public class ThreadPoolEchoServer { public static void main(String[] args) throws IOException { Inicialización de ServerSocket servSock = new ServerSocket(20007); pool de threads Executor service = Executors.newCachedThreadPool(); while (!Thread.interrupted()) { Socket clntSock = servSock.accept(); service.execute(new EchoWorker(clntSock)); } } }
  • 11. An Echo Server • Java OIO public class ThreadPoolEchoServer { public static void main(String[] args) throws IOException { ServerSocket servSock = new ServerSocket(20007); Executor service = Executors.newCachedThreadPool(); while (!Thread.interrupted()) { Se acepta conexión Socket clntSock = servSock.accept(); service.execute(new EchoWorker(clntSock)); } } }
  • 12. An Echo Server • Java OIO public class ThreadPoolEchoServer { public static void main(String[] args) throws IOException { ServerSocket servSock = new ServerSocket(20007); Executor service = Executors.newCachedThreadPool(); while (!Thread.interrupted()) { Socket clntSock = servSock.accept(); service.execute(new EchoWorker(clntSock)); } } Se ejecuta worker thread }
  • 13. An Echo Server • Java OIO public class ThreadPoolEchoServer { public static void main(String[] args) throws IOException { ServerSocket servSock = new ServerSocket(20007); Executor service = Executors.newCachedThreadPool(); while (!Thread.interrupted()) { Socket clntSock = servSock.accept(); service.execute(new EchoWorker(clntSock)); } } }
  • 14. An Echo Server • Java OIO public class EchoWorker implements Runnable { public EchoWorker(final Socket s) { this.socket = s; } public void run() { try { InputStream in = this.socket.getInputStream(); OutputStream out = this.socket.getOutputStream(); int recvMsgSize; byte[] receiveBuf = new byte[256]; while ((recvMsgSize = in.read(receiveBuf)) != -1) { out.write(receiveBuf, 0, recvMsgSize); } } catch (IOException e) { // ... } finally { try { this.socket.close(); } catch (IOException e) { // ... } } } }
  • 15. An Echo Server • Java OIO public class EchoWorker implements Runnable { public EchoWorker(final Socket s) { this.socket = s; } Obtención de Streams de public void run() { entrada y salida try { InputStream in = this.socket.getInputStream(); OutputStream out = this.socket.getOutputStream(); int recvMsgSize; byte[] receiveBuf = new byte[256]; while ((recvMsgSize = in.read(receiveBuf)) != -1) { out.write(receiveBuf, 0, recvMsgSize); } } catch (IOException e) { // ... } finally { try { this.socket.close(); } catch (IOException e) { // ... } } } }
  • 16. An Echo Server • Java OIO public class EchoWorker implements Runnable { public EchoWorker(final Socket s) { this.socket = s; } public void run() { try { InputStream in = this.socket.getInputStream(); OutputStream out = this.socket.getOutputStream(); int recvMsgSize; Se lee hasta que el cliente cierre la conexión byte[] receiveBuf = new byte[256]; (bloqueante) while ((recvMsgSize = in.read(receiveBuf)) != -1) { out.write(receiveBuf, 0, recvMsgSize); } } catch (IOException e) { // ... } finally { try { this.socket.close(); } catch (IOException e) { // ... } } } }
  • 17. An Echo Server • Java OIO public class EchoWorker implements Runnable { public EchoWorker(final Socket s) { this.socket = s; } public void run() { try { InputStream in = this.socket.getInputStream(); OutputStream out = this.socket.getOutputStream(); int recvMsgSize; byte[] receiveBuf = new byte[256]; while ((recvMsgSize = in.read(receiveBuf)) != -1) { out.write(receiveBuf, 0, recvMsgSize); } Se reenvia lo leido al } catch (IOException e) { // ... cliente (bloqueante) } finally { try { this.socket.close(); } catch (IOException e) { // ... } } } }
  • 18. An Echo Server • Java OIO public class EchoWorker implements Runnable { public EchoWorker(final Socket s) { this.socket = s; } public void run() { try { InputStream in = this.socket.getInputStream(); OutputStream out = this.socket.getOutputStream(); int recvMsgSize; byte[] receiveBuf = new byte[256]; while ((recvMsgSize = in.read(receiveBuf)) != -1) { out.write(receiveBuf, 0, recvMsgSize); } } catch (IOException e) { // ... } finally { try { this.socket.close(); } catch (IOException e) { // ... } el socket Se cierra } } }
  • 19. An Echo Server • Java OIO public class EchoWorker implements Runnable { public EchoWorker(final Socket s) { this.socket = s; } public void run() { try { InputStream in = this.socket.getInputStream(); OutputStream out = this.socket.getOutputStream(); int recvMsgSize; byte[] receiveBuf = new byte[256]; while ((recvMsgSize = in.read(receiveBuf)) != -1) { out.write(receiveBuf, 0, recvMsgSize); } } catch (IOException e) { // ... } finally { try { this.socket.close(); } catch (IOException e) { // ... } } } }
  • 21. El Camino Tradicional: Problemas ✓ Estado compartido entre clientes
  • 22. El Camino Tradicional: Problemas ✓ Estado compartido entre clientes ✓Sincronización
  • 23. El Camino Tradicional: Problemas ✓ Estado compartido entre clientes ✓Sincronización ✓ Priorización de clientes
  • 24. El Camino Tradicional: Problemas ✓ Estado compartido entre clientes ✓Sincronización ✓ Priorización de clientes ✓ Alta escala (C10K)
  • 25. El Camino Tradicional: Problemas ✓ Estado compartido entre clientes ✓Sincronización ✓ Priorización de clientes ✓ Alta escala (C10K) ✓ Conexiones Persistentes
  • 26. El Camino Tradicional: Problemas ✓ Estado compartido entre clientes ✓Sincronización ✓ Priorización de clientes ✓ Alta escala (C10K) ✓ Conexiones Persistentes ✓ Context Switching Overhead
  • 27. El Camino Tradicional: Problemas ✓ Estado compartido entre clientes ✓Sincronización ✓ Priorización de clientes ✓ Alta escala (C10K) ✓ Conexiones Persistentes ✓ Context Switching Overhead ✓ Consumo de memoria
  • 28. Non Blocking IO: What’s the story? ✓ Modelo orientado a eventos Reactor Pattern ✓ Un único thread de procesamiento ✓ Uso de Readiness Notification y Non Blocking IO Leer Cliente Decodificar read events Procesar Cliente Reactor write events Codificar Cliente Enviar
  • 29. Non Blocking IO vs. Blocking IO
  • 30. Non Blocking IO en Java
  • 31. Non Blocking IO en Java ✓ Java NIO
  • 32. Non Blocking IO en Java ✓ Java NIO ✓ Frameworks
  • 33. Non Blocking IO en Java ✓ Java NIO ✓ Frameworks ✓ Apache Mina
  • 34. Non Blocking IO en Java ✓ Java NIO ✓ Frameworks ✓ Apache Mina ✓ JBoss Netty
  • 35. Non Blocking IO en Java - NIO Diseño Java NIO Dispatcher EventHandler * 1 Selector SelectionKey SelectableChannel SocketChannel java.nio.channels
  • 36. An Echo Server • Java NIO public class Dispatcher { public Dispatcher(final int port, final EventHandler handler) { ... } public void run() throws IOException { Selector selector = Selector.open(); ServerSocketChannel listenChannel = ServerSocketChannel.open(); listenChannel.socket().bind(new InetSocketAddress(this.port)); listenChannel.configureBlocking(false); listenChannel.register(selector, SelectionKey.OP_ACCEPT); while (!Thread.interrupted()) { if (selector.select(3000) == 0) continue; Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator(); while (keyIter.hasNext()) { SelectionKey key = keyIter.next(); if (key.isAcceptable()) { handler.handleAccept(key); } if (key.isReadable()) { handler.handleRead(key); } if (key.isValid() && key.isWritable()) { handler.handleWrite(key); } keyIter.remove(); // remove from set of selected keys } } } }
  • 37. An Echo Server • Java NIO public class Dispatcher { public Dispatcher(final int port, final EventHandler handler) { ... Crea selector para } monitorear sockets public void run() throws IOException { pasivos y conexiones Selector selector = Selector.open(); ServerSocketChannel listenChannel = ServerSocketChannel.open(); listenChannel.socket().bind(new InetSocketAddress(this.port)); listenChannel.configureBlocking(false); listenChannel.register(selector, SelectionKey.OP_ACCEPT); while (!Thread.interrupted()) { if (selector.select(3000) == 0) continue; Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator(); while (keyIter.hasNext()) { SelectionKey key = keyIter.next(); if (key.isAcceptable()) { handler.handleAccept(key); } if (key.isReadable()) { handler.handleRead(key); } if (key.isValid() && key.isWritable()) { handler.handleWrite(key); } keyIter.remove(); // remove from set of selected keys } } } }
  • 38. An Echo Server • Java NIO public class Dispatcher { public Dispatcher(final int port, final EventHandler handler) { ... } public void run() throws IOException { Inicialización de socket Selector selector = Selector.open(); para escucha en forma no bloqueante ServerSocketChannel listenChannel = ServerSocketChannel.open(); listenChannel.socket().bind(new InetSocketAddress(this.port)); listenChannel.configureBlocking(false); listenChannel.register(selector, SelectionKey.OP_ACCEPT); while (!Thread.interrupted()) { if (selector.select(3000) == 0) continue; Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator(); while (keyIter.hasNext()) { SelectionKey key = keyIter.next(); if (key.isAcceptable()) { handler.handleAccept(key); } if (key.isReadable()) { handler.handleRead(key); } if (key.isValid() && key.isWritable()) { handler.handleWrite(key); } keyIter.remove(); // remove from set of selected keys } } } }
  • 39. An Echo Server • Java NIO public class Dispatcher { public Dispatcher(final int port, final EventHandler handler) { ... } public void run() throws IOException { Selector selector = Selector.open(); ServerSocketChannel listenChannel = ServerSocketChannel.open(); listenChannel.socket().bind(new InetSocketAddress(this.port)); listenChannel.configureBlocking(false); Registra socket listenChannel.register(selector, SelectionKey.OP_ACCEPT); declarando interés en nuevas conexiones while (!Thread.interrupted()) { if (selector.select(3000) == 0) continue; Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator(); while (keyIter.hasNext()) { SelectionKey key = keyIter.next(); if (key.isAcceptable()) { handler.handleAccept(key); } if (key.isReadable()) { handler.handleRead(key); } if (key.isValid() && key.isWritable()) { handler.handleWrite(key); } keyIter.remove(); // remove from set of selected keys } } } }
  • 40. An Echo Server • Java NIO public class Dispatcher { public Dispatcher(final int port, final EventHandler handler) { ... } public void run() throws IOException { Selector selector = Selector.open(); ServerSocketChannel listenChannel = ServerSocketChannel.open(); listenChannel.socket().bind(new InetSocketAddress(this.port)); Monitorea actividad en listenChannel.configureBlocking(false); todos los sockets listenChannel.register(selector, SelectionKey.OP_ACCEPT); registrados while (!Thread.interrupted()) { if (selector.select(3000) == 0) continue; Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator(); while (keyIter.hasNext()) { SelectionKey key = keyIter.next(); if (key.isAcceptable()) { handler.handleAccept(key); } if (key.isReadable()) { handler.handleRead(key); } if (key.isValid() && key.isWritable()) { handler.handleWrite(key); } keyIter.remove(); // remove from set of selected keys } } } }
  • 41. An Echo Server • Java NIO public class Dispatcher { public Dispatcher(final int port, final EventHandler handler) { ... } public void run() throws IOException { Selector selector = Selector.open(); ServerSocketChannel listenChannel = ServerSocketChannel.open(); listenChannel.socket().bind(new InetSocketAddress(this.port)); listenChannel.configureBlocking(false); listenChannel.register(selector, SelectionKey.OP_ACCEPT); while (!Thread.interrupted()) { if (selector.select(3000) == 0) continue; Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator(); while (keyIter.hasNext()) { Detecta y dispara eventos SelectionKey key = keyIter.next(); de acuerdo al tipo if (key.isAcceptable()) { handler.handleAccept(key); } if (key.isReadable()) { handler.handleRead(key); } if (key.isValid() && key.isWritable()) { handler.handleWrite(key); } keyIter.remove(); // remove from set of selected keys } } } }
  • 42. An Echo Server • Java NIO public class Dispatcher { public Dispatcher(final int port, final EventHandler handler) { ... } public void run() throws IOException { Selector selector = Selector.open(); ServerSocketChannel listenChannel = ServerSocketChannel.open(); listenChannel.socket().bind(new InetSocketAddress(this.port)); listenChannel.configureBlocking(false); listenChannel.register(selector, SelectionKey.OP_ACCEPT); while (!Thread.interrupted()) { if (selector.select(3000) == 0) continue; Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator(); while (keyIter.hasNext()) { SelectionKey key = keyIter.next(); if (key.isAcceptable()) { handler.handleAccept(key); } if (key.isReadable()) { handler.handleRead(key); } if (key.isValid() && key.isWritable()) { handler.handleWrite(key); } keyIter.remove(); // remove from set of selected keys } } } }
  • 43. An Echo Server • Java NIO public class EchoProtocolEventHandler implements EventHandler { private static final int BUFSIZE = 256; public void handleAccept(SelectionKey key) throws IOException { SocketChannel clntChan = ((ServerSocketChannel) key.channel()).accept(); clntChan.configureBlocking(false); clntChan.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(BUFSIZE)); } public void handleRead(SelectionKey key) throws IOException { SocketChannel clntChan = (SocketChannel) key.channel(); ByteBuffer buf = (ByteBuffer) key.attachment(); long bytesRead = clntChan.read(buf); if (bytesRead == -1) { // Did the other end close? clntChan.close(); } else if (bytesRead > 0) { key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); } } public void handleWrite(SelectionKey key) throws IOException { ByteBuffer buf = (ByteBuffer) key.attachment(); buf.flip(); SocketChannel clntChan = (SocketChannel) key.channel(); clntChan.write(buf); if (!buf.hasRemaining()) { key.interestOps(SelectionKey.OP_READ); } buf.compact(); } }
  • 44. An Echo Server • Java NIO public class EchoProtocolEventHandler implements EventHandler { private static final int BUFSIZE = 256; Acepta nueva conexión public void handleAccept(SelectionKey key) throws IOException { SocketChannel clntChan = ((ServerSocketChannel) key.channel()).accept(); clntChan.configureBlocking(false); clntChan.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(BUFSIZE)); } public void handleRead(SelectionKey key) throws IOException { SocketChannel clntChan = (SocketChannel) key.channel(); ByteBuffer buf = (ByteBuffer) key.attachment(); long bytesRead = clntChan.read(buf); if (bytesRead == -1) { // Did the other end close? clntChan.close(); } else if (bytesRead > 0) { key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); } } public void handleWrite(SelectionKey key) throws IOException { ByteBuffer buf = (ByteBuffer) key.attachment(); buf.flip(); SocketChannel clntChan = (SocketChannel) key.channel(); clntChan.write(buf); if (!buf.hasRemaining()) { key.interestOps(SelectionKey.OP_READ); } buf.compact(); } }
  • 45. An Echo Server • Java NIO public class EchoProtocolEventHandler implements EventHandler { private static final int BUFSIZE = 256; public void handleAccept(SelectionKey key) throws IOException { SocketChannel clntChan = ((ServerSocketChannel) key.channel()).accept(); clntChan.configureBlocking(false); clntChan.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(BUFSIZE)); } Registra nuevo socket public void handleRead(SelectionKey key) throws IOException { declarando interés en SocketChannel clntChan = (SocketChannel) key.channel(); lectura y asocia buffer ByteBuffer buf = (ByteBuffer) key.attachment(); long bytesRead = clntChan.read(buf); if (bytesRead == -1) { // Did the other end close? clntChan.close(); } else if (bytesRead > 0) { key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); } } public void handleWrite(SelectionKey key) throws IOException { ByteBuffer buf = (ByteBuffer) key.attachment(); buf.flip(); SocketChannel clntChan = (SocketChannel) key.channel(); clntChan.write(buf); if (!buf.hasRemaining()) { key.interestOps(SelectionKey.OP_READ); } buf.compact(); } }
  • 46. An Echo Server • Java NIO public class EchoProtocolEventHandler implements EventHandler { private static final int BUFSIZE = 256; public void handleAccept(SelectionKey key) throws IOException { SocketChannel clntChan = ((ServerSocketChannel) key.channel()).accept(); clntChan.configureBlocking(false); clntChan.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(BUFSIZE)); } public void handleRead(SelectionKey key) throws IOException { SocketChannel clntChan = (SocketChannel) key.channel(); ByteBuffer buf = (ByteBuffer) key.attachment(); long bytesRead = clntChan.read(buf); Lee datos en buffer if (bytesRead == -1) { // Did the other end close? asociado clntChan.close(); } else if (bytesRead > 0) { key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); } } public void handleWrite(SelectionKey key) throws IOException { ByteBuffer buf = (ByteBuffer) key.attachment(); buf.flip(); SocketChannel clntChan = (SocketChannel) key.channel(); clntChan.write(buf); if (!buf.hasRemaining()) { key.interestOps(SelectionKey.OP_READ); } buf.compact(); } }
  • 47. An Echo Server • Java NIO public class EchoProtocolEventHandler implements EventHandler { private static final int BUFSIZE = 256; public void handleAccept(SelectionKey key) throws IOException { SocketChannel clntChan = ((ServerSocketChannel) key.channel()).accept(); clntChan.configureBlocking(false); clntChan.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(BUFSIZE)); } public void handleRead(SelectionKey key) throws IOException { SocketChannel clntChan = (SocketChannel) key.channel(); ByteBuffer buf = (ByteBuffer) key.attachment(); long bytesRead = clntChan.read(buf); if (bytesRead == -1) { // Did the other end close? clntChan.close(); } else if (bytesRead > 0) { key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); Detecta fin de conexión } } public void handleWrite(SelectionKey key) throws IOException { ByteBuffer buf = (ByteBuffer) key.attachment(); buf.flip(); SocketChannel clntChan = (SocketChannel) key.channel(); clntChan.write(buf); if (!buf.hasRemaining()) { key.interestOps(SelectionKey.OP_READ); } buf.compact(); } }
  • 48. An Echo Server • Java NIO public class EchoProtocolEventHandler implements EventHandler { private static final int BUFSIZE = 256; public void handleAccept(SelectionKey key) throws IOException { SocketChannel clntChan = ((ServerSocketChannel) key.channel()).accept(); clntChan.configureBlocking(false); clntChan.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(BUFSIZE)); } public void handleRead(SelectionKey key) throws IOException { SocketChannel clntChan = (SocketChannel) key.channel(); ByteBuffer buf = (ByteBuffer) key.attachment(); long bytesRead = clntChan.read(buf); if (bytesRead == -1) { // Did the other end close? clntChan.close(); } else if (bytesRead > 0) { key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); } } Declara interés en public void handleWrite(SelectionKey key) throws IOException { escritura si hay datos a ByteBuffer buf = (ByteBuffer) key.attachment(); escribir buf.flip(); SocketChannel clntChan = (SocketChannel) key.channel(); clntChan.write(buf); if (!buf.hasRemaining()) { key.interestOps(SelectionKey.OP_READ); } buf.compact(); } }
  • 49. An Echo Server • Java NIO public class EchoProtocolEventHandler implements EventHandler { private static final int BUFSIZE = 256; public void handleAccept(SelectionKey key) throws IOException { SocketChannel clntChan = ((ServerSocketChannel) key.channel()).accept(); clntChan.configureBlocking(false); clntChan.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(BUFSIZE)); } public void handleRead(SelectionKey key) throws IOException { SocketChannel clntChan = (SocketChannel) key.channel(); ByteBuffer buf = (ByteBuffer) key.attachment(); long bytesRead = clntChan.read(buf); if (bytesRead == -1) { // Did the other end close? clntChan.close(); } else if (bytesRead > 0) { key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); } } public void handleWrite(SelectionKey key) throws IOException { ByteBuffer buf = (ByteBuffer) key.attachment(); buf.flip(); SocketChannel clntChan = (SocketChannel) key.channel(); clntChan.write(buf); Envia datos al socket if (!buf.hasRemaining()) { key.interestOps(SelectionKey.OP_READ); } buf.compact(); } }
  • 50. An Echo Server • Java NIO public class EchoProtocolEventHandler implements EventHandler { private static final int BUFSIZE = 256; public void handleAccept(SelectionKey key) throws IOException { SocketChannel clntChan = ((ServerSocketChannel) key.channel()).accept(); clntChan.configureBlocking(false); clntChan.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(BUFSIZE)); } public void handleRead(SelectionKey key) throws IOException { SocketChannel clntChan = (SocketChannel) key.channel(); ByteBuffer buf = (ByteBuffer) key.attachment(); long bytesRead = clntChan.read(buf); if (bytesRead == -1) { // Did the other end close? clntChan.close(); } else if (bytesRead > 0) { key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); } } public void handleWrite(SelectionKey key) throws IOException { ByteBuffer buf = (ByteBuffer) key.attachment(); buf.flip(); SocketChannel clntChan = (SocketChannel) key.channel(); clntChan.write(buf); if (!buf.hasRemaining()) { key.interestOps(SelectionKey.OP_READ); } Revoca interés en escritura buf.compact(); si no hay nada para escribir } }
  • 51. An Echo Server • Java NIO public class EchoProtocolEventHandler implements EventHandler { private static final int BUFSIZE = 256; public void handleAccept(SelectionKey key) throws IOException { SocketChannel clntChan = ((ServerSocketChannel) key.channel()).accept(); clntChan.configureBlocking(false); clntChan.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(BUFSIZE)); } public void handleRead(SelectionKey key) throws IOException { SocketChannel clntChan = (SocketChannel) key.channel(); ByteBuffer buf = (ByteBuffer) key.attachment(); long bytesRead = clntChan.read(buf); if (bytesRead == -1) { // Did the other end close? clntChan.close(); } else if (bytesRead > 0) { key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); } } public void handleWrite(SelectionKey key) throws IOException { ByteBuffer buf = (ByteBuffer) key.attachment(); buf.flip(); SocketChannel clntChan = (SocketChannel) key.channel(); clntChan.write(buf); if (!buf.hasRemaining()) { key.interestOps(SelectionKey.OP_READ); } buf.compact(); } }
  • 52. An Echo Server • Java NIO public interface EventHandler { void handleAccept(SelectionKey key) throws IOException; void handleRead(SelectionKey key) throws IOException; void handleWrite(SelectionKey key) throws IOException; } public class NIOEchoServer { public static void main(String[] args) throws IOException { Dispatcher dispatcher = new Dispatcher(20007, new EchoProtocolEventHandler()); dispatcher.run(); } }
  • 53. Netty!! from Netty Homepage The Netty project is an effort to provide an asynchronous event-driven network application framework and tools for rapid development of maintainable high performance & high scalability protocol servers & clients
  • 54. Netty!! from Netty Homepage The Netty project is an effort to provide an asynchronous event-driven network application framework and tools for rapid development of maintainable high performance & high scalability protocol servers & clients
  • 55. Netty!! from Netty Homepage The Netty project is an effort to provide an asynchronous event-driven application network framework and tools for rapid development of maintainable high performance & high scalability protocol servers & clients
  • 56. Netty!! from Netty Homepage The Netty project is an effort to provide an asynchronous event-driven network application framework and tools for rapid development of high performance & high scalability maintainable protocol servers & clients
  • 57. Netty!! from Netty Homepage The Netty project is an effort to provide an asynchronous event-driven network application rapid development framework and tools for of maintainable high performance & high scalability protocol servers & clients
  • 58. Netty!! from Netty Homepage The Netty project is an effort to provide an asynchronous event-driven network application framework and tools for rapid development of maintainable high performance & high scalability protocol servers & clients Warning! Netty no es un WebServer
  • 59. Netty Model • Channels creates handles ChannelFactory Channel ChannelPipeline es with & writ generates is sorted list of s read handles ChannelBuffer ChannelEvent ChannelHandler ✓ Representa a una conexion P2P (point to point) ✓ Abstrae UDP / TCP ✓ Abstrae NIO / OIO ✓ API interacción conexión (abrir, cerrar, escribir, leer)
  • 60. Netty Model • ChannelBuffers creates handles ChannelFactory Channel ChannelPipeline es with & writ generates is sorted list of s read handles ChannelBuffer ChannelEvent ChannelHandler
  • 61. Netty Model • ChannelBuffers creates handles ChannelFactory Channel ChannelPipeline es with & writ generates is sorted list of s read handles ChannelBuffer ChannelEvent ChannelHandler ✓ Abstrae de NIO Buffers & byte arrays ✓ API simplificada respecto NIO Buffers ✓ Toda lectura y escritura se hace con ellos
  • 62. Netty Model • ChannelFactory creates handles ChannelFactory Channel ChannelPipeline es with & writ generates is sorted list of s read handles ChannelBuffer ChannelEvent ChannelHandler
  • 63. Netty Model • ChannelFactory creates handles ChannelFactory Channel ChannelPipeline es with & writ generates is sorted list of s read handles ChannelBuffer ChannelEvent ChannelHandler ✓ Crear Channels ✓ ChannelFactory impl. para UDP / TCP y OIO / NIO ✓ Non Blocking con: NioServerSocketChannelFactory
  • 64. Netty Model • ChannelEvent creates handles ChannelFactory Channel ChannelPipeline es with & writ generates is sorted list of s read handles ChannelBuffer ChannelEvent ChannelHandler
  • 65. Netty Model • ChannelEvent creates handles ChannelFactory Channel ChannelPipeline es with & writ generates is sorted list of s read handles ChannelBuffer ChannelEvent ChannelHandler ✓ Representa un evento I/O asociado a un Channel ✓ Puede ser upstream (entrada) or downstream (salida) ✓ Se pueden crear eventos custom ✓ Algunos tipos de evento: ★ messageReceived ★ channelOpen ★ channelClosed ★ write
  • 66. Netty Model • ChannelPipeline creates handles ChannelFactory Channel ChannelPipeline es with & writ generates is sorted list of s read handles ChannelBuffer ChannelEvent ChannelHandler
  • 67. Netty Model • ChannelPipeline creates handles ChannelFactory Channel ChannelPipeline es with & writ generates is sorted list of s read handles ChannelBuffer ChannelEvent ChannelHandler ✓ Asociado a un Channel ✓ Atrapa y Handlea los ChannelEvents ✓ Implementa el patron Intercepting Filter
  • 68. Netty Model • ChannelHandler creates handles ChannelFactory Channel ChannelPipeline es with & writ generates is sorted list of s read handles ChannelBuffer ChannelEvent ChannelHandler
  • 69. Netty Model • ChannelHandler creates handles ChannelFactory Channel ChannelPipeline es with & writ generates is sorted list of s read handles ChannelBuffer ChannelEvent ChannelHandler ✓ Building block de un ChannelPipeline ✓ Handlea ChannelEvents (upstream y/o downstream) ✓ Decide sobre el forwarding de eventos a sus pares upstream Handler Handler Handler Handler event N -1 First Last 2nd downstream event
  • 70. An Echo Server • Netty NIO Main Class public class EchoServer { public static void main(String[] args) throws Exception { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); // Set up the pipeline factory. bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() throws Exception { return Channels.pipeline(new EchoServerHandler()); } }); // Bind and start to accept incoming connections. bootstrap.bind(new InetSocketAddress(8080)); } } Ejemplo en: http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/echo/package-summary.html
  • 71. An Echo Server • Netty NIO Main Class public class EchoServer { Utility Class para public static void main(String[] args) throws Exception {inicializar un Server // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); // Set up the pipeline factory. bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() throws Exception { return Channels.pipeline(new EchoServerHandler()); } }); // Bind and start to accept incoming connections. bootstrap.bind(new InetSocketAddress(8080)); } } Ejemplo en: http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/echo/package-summary.html
  • 72. An Echo Server • Netty NIO Main Class public class EchoServer { public static void main(String[] args) throws Exception { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( ChannelFactory para Tcp new NioServerSocketChannelFactory( w/ NIO Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); // Set up the pipeline factory. bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() throws Exception { return Channels.pipeline(new EchoServerHandler()); } }); // Bind and start to accept incoming connections. bootstrap.bind(new InetSocketAddress(8080)); } } Ejemplo en: http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/echo/package-summary.html
  • 73. An Echo Server • Netty NIO Main Class public class EchoServer { public static void main(String[] args) throws Exception { // Configure the server. Boss pool thread ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); Workers pool thread // Set up the pipeline factory. bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() throws Exception { return Channels.pipeline(new EchoServerHandler()); } }); // Bind and start to accept incoming connections. bootstrap.bind(new InetSocketAddress(8080)); } } Ejemplo en: http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/echo/package-summary.html
  • 74. An Echo Server • Netty NIO Main Class public class EchoServer { public static void main(String[] args) throws Exception { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); // Set up the pipeline factory. bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() throws Exception { ChannelPipelineFactory para cada nuevo Channel return Channels.pipeline(new EchoServerHandler()); establcido } }); // Bind and start to accept incoming connections. bootstrap.bind(new InetSocketAddress(8080)); } } Ejemplo en: http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/echo/package-summary.html
  • 75. An Echo Server • Netty NIO Main Class public class EchoServer { public static void main(String[] args) throws Exception { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); // Set up the pipeline factory. bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() throws Exception { return Channels.pipeline(new EchoServerHandler()); } }); Un solo handler. El echo Handler // Bind and start to accept incoming connections. bootstrap.bind(new InetSocketAddress(8080)); } } Ejemplo en: http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/echo/package-summary.html
  • 76. An Echo Server • Netty NIO Main Class public class EchoServer { public static void main(String[] args) throws Exception { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); // Set up the pipeline factory. bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() throws Exception { return Channels.pipeline(new EchoServerHandler()); } }); // Bind and start to accept incoming connections. bootstrap.bind(new InetSocketAddress(8080)); } } Finalmente inicializamos el servidor Ejemplo en: http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/echo/package-summary.html
  • 77. An Echo Server • Netty NIO Handler public class EchoServerHandler extends SimpleChannelHandler { @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { e.getChannel().write(e.getMessage()); } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { e.getCause().printStackTrace(); Channel ch = e.getChannel(); ch.close(); } } Ejemplo en: http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/echo/package-summary.html
  • 78. An Echo Server • Netty NIO Handler Utility class para handlear public class EchoServerHandler extends SimpleChannelHandler { eventos típicos @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { e.getChannel().write(e.getMessage()); } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { e.getCause().printStackTrace(); Channel ch = e.getChannel(); ch.close(); } } Ejemplo en: http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/echo/package-summary.html
  • 79. An Echo Server • Netty NIO Handler public class EchoServerHandler extends SimpleChannelHandler { @Override Event Handler para public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { nuevo mensaje e.getChannel().write(e.getMessage()); } @Override Event Handler para void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { public excepciones e.getCause().printStackTrace(); Channel ch = e.getChannel(); ch.close(); } } Ejemplo en: http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/echo/package-summary.html
  • 80. An Echo Server • Netty NIO Handler public class EchoServerHandler extends SimpleChannelHandler { @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { e.getChannel().write(e.getMessage()); } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { e.getCause().printStackTrace(); Contexto del Canal Channel ch = e.getChannel(); Permite interactuar con su ch.close(); pipeline } } Ejemplo en: http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/echo/package-summary.html
  • 81. An Echo Server • Netty NIO Handler public class EchoServerHandler extends SimpleChannelHandler { @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { e.getChannel().write(e.getMessage()); } Interacción con el Channel: Lectura y Escritura @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { e.getCause().printStackTrace(); Channel ch = e.getChannel(); ch.close(); } } Ejemplo en: http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/echo/package-summary.html
  • 82. An Echo Server • Netty OIO Vuelta a OIO! public class EchoServer { public static void main(String[] args) throws Exception { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new OioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); // Set up the pipeline factory. bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() throws Exception { return Channels.pipeline(new EchoServerHandler()); } }); // Bind and start to accept incoming connections. bootstrap.bind(new InetSocketAddress(8080)); } }
  • 83. An Echo Server • Netty OIO Vuelta a OIO! public class EchoServer { public static void main(String[] args) throws Exception { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( ChannelFactory para Tcp new OioServerSocketChannelFactory( w/ OIO Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); // Set up the pipeline factory. bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() throws Exception { return Channels.pipeline(new EchoServerHandler()); } }); // Bind and start to accept incoming connections. bootstrap.bind(new InetSocketAddress(8080)); } }
  • 84. A Distributed Logger • Diseño Protocolo ✓ Formato textual, de linea ✓ Paquete tamaño variable ✓ Mensaje por fin de linea ✓ Formato: “${level} - ${mensaje}” DEBUG - Algo esta mal!!
  • 85. Framer Handler Decoder Handler pipeline LoggerPrinter Handler A Distributed Logger • Diseño
  • 86. Framer Handler Decoder Handler LoggerPrinter Handler A Distributed Logger • Framer
  • 87. A Distributed Logger • Framer Decoder Handler Framer Handler LoggerPrinter Handler Framer import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder; import org.jboss.netty.handler.codec.frame.Delimiters; public class LoggerFramerHandler extends DelimiterBasedFrameDecoder { public LoggerFramerHandler() { super(8000, Delimiters.lineDelimiter()); } }
  • 88. A Distributed Logger • Framer Decoder Handler Framer Handler LoggerPrinter Handler Framer import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder; import org.jboss.netty.handler.codec.frame.Delimiters; public class LoggerFramerHandler extends DelimiterBasedFrameDecoder { public LoggerFramerHandler() { Framer para demarcar super(8000, Delimiters.lineDelimiter()); paquetes a través de un } delimitador }
  • 89. A Distributed Logger • Framer Decoder Handler Framer Handler LoggerPrinter Handler Framer import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder; import org.jboss.netty.handler.codec.frame.Delimiters; public class LoggerFramerHandler extends DelimiterBasedFrameDecoder { public LoggerFramerHandler() { super(8000, Delimiters.lineDelimiter()); } } Delimitador para lineas
  • 90. Framer Handler Decoder Handler LoggerPrinter Handler A Distributed Logger • Framer
  • 91. Framer Handler Decoder Handler LoggerPrinter Handler A Distributed Logger • Decoder
  • 92. A Distributed Logger • Decoder Decoder Handler Framer Handler LoggerPrinter Handler Decoder @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { Charset ch = Charset.defaultCharset(); String msg = ((ChannelBuffer) e.getMessage()).toString(ch); String[] args = msg.split("-", 2); LogEvent logEvent = new LogEvent(Level.valueOf(args[0].trim()), args[1].trim()); Channels.fireMessageReceived(ctx, logEvent); }
  • 93. A Distributed Logger • Decoder Decoder Handler Framer Handler LoggerPrinter Handler Decoder @Override El framer deja un public void messageReceived(ChannelHandlerContext ctx, MessageEventmsg { ChannelBuffer como e) Charset ch = Charset.defaultCharset(); String msg = ((ChannelBuffer) e.getMessage()).toString(ch); String[] args = msg.split("-", 2); LogEvent logEvent = new LogEvent(Level.valueOf(args[0].trim()), args[1].trim()); Channels.fireMessageReceived(ctx, logEvent); }
  • 94. A Distributed Logger • Decoder Decoder Handler Framer Handler LoggerPrinter Handler Decoder @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { Charset ch = Charset.defaultCharset(); String msg = ((ChannelBuffer) e.getMessage()).toString(ch); String[] args = msg.split("-", 2); parseo y creación de un LogEvent LogEvent logEvent = new LogEvent(Level.valueOf(args[0].trim()), args[1].trim()); Channels.fireMessageReceived(ctx, logEvent); }
  • 95. A Distributed Logger • Decoder Decoder Handler Framer Handler LoggerPrinter Handler Decoder @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { Charset ch = Charset.defaultCharset(); String msg = ((ChannelBuffer) e.getMessage()).toString(ch); String[] args = msg.split("-", 2); LogEvent logEvent = new LogEvent(Level.valueOf(args[0].trim()), args[1].trim()); Channels.fireMessageReceived(ctx, logEvent); } propago el mensaje, como LogEvent
  • 96. Framer Handler Decoder Handler LoggerPrinter Handler A Distributed Logger • Decoder
  • 97. Framer Handler Decoder Handler LoggerPrinter Handler A Distributed Logger • Printer
  • 98. A Distributed Logger • Printer Decoder Handler Framer Handler LoggerPrinter Handler Printer @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { LogEvent logEvent = (LogEvent) e.getMessage(); System.out.println(logEvent); }
  • 99. A Distributed Logger • Printer Decoder Handler Framer Handler LoggerPrinter Handler Printer El msg ahora es un @Override LogEvent public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { LogEvent logEvent = (LogEvent) e.getMessage(); System.out.println(logEvent); }
  • 100. A Distributed Logger • Printer Decoder Handler Framer Handler LoggerPrinter Handler Printer @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { LogEvent logEvent = (LogEvent) e.getMessage(); System.out.println(logEvent); }
  • 101. Conclusiones ✓ Non-Blocking IO ✓ Importa! ✓ Aplicaciones altamente concurrentes (c10k) ✓ Netty ✓ java nio made easy ✓ modelo flexible para crear servidores NIO (o OIO)
  • 102. ¿¿ Preguntas ?? We are hiring! Apply at jobs@zaubersoftware.com

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n
  67. \n
  68. \n
  69. \n
  70. \n
  71. \n
  72. \n
  73. \n
  74. \n
  75. \n
  76. \n
  77. \n
  78. \n
  79. \n
  80. \n
  81. \n
  82. \n
  83. \n
  84. \n
  85. \n
  86. \n
  87. \n
  88. \n
  89. \n
  90. \n
  91. \n
  92. \n
  93. \n
  94. \n
  95. \n
  96. \n
  97. \n
  98. \n
  99. \n
  100. \n
  101. \n
  102. \n
  103. \n
  104. \n
  105. \n
  106. \n
  107. \n
  108. \n
  109. \n
  110. \n
  111. \n
  112. \n
  113. \n
  114. \n
  115. \n
  116. \n
  117. \n
  118. \n
  119. \n
  120. \n
  121. \n
  122. \n
  123. \n
  124. \n
  125. \n
  126. \n
  127. \n
  128. \n
  129. \n
  130. \n
  131. \n
  132. \n
  133. \n
  134. \n
  135. \n
  136. \n
  137. \n
  138. \n
  139. \n
  140. \n
  141. \n
  142. \n
  143. \n
  144. \n
  145. \n
  146. \n
  147. \n
  148. \n
  149. \n
  150. \n
  151. \n
  152. \n
  153. \n
  154. \n
  155. \n
  156. \n
  157. \n
  158. \n
  159. \n
  160. \n
  161. \n
  162. \n
  163. \n
  164. \n
  165. \n
  166. \n
  167. \n
  168. \n
  169. \n
  170. \n
  171. \n
  172. \n
  173. \n
  174. \n
  175. \n
  176. \n
  177. \n
  178. \n
  179. \n
  180. \n
  181. \n
  182. \n
  183. \n
  184. \n
  185. \n
  186. \n
  187. \n
  188. \n
  189. \n
  190. \n
  191. \n
  192. \n
  193. \n
  194. \n
  195. \n
  196. \n
  197. \n
  198. \n
  199. \n
  200. \n
  201. \n
  202. \n
  203. \n
  204. \n
  205. \n
  206. \n
  207. \n
  208. \n
  209. \n
  210. \n
  211. \n
  212. \n
  213. \n
  214. \n
  215. \n
  216. \n
  217. \n
  218. \n
  219. \n
  220. \n
  221. \n
  222. \n
  223. \n
  224. \n
  225. \n
  226. \n
  227. \n
  228. \n
  229. \n
  230. \n
  231. \n
  232. \n
  233. \n
  234. \n
  235. \n
  236. \n
  237. \n
  238. \n
  239. \n
  240. \n
  241. \n
  242. \n
  243. \n
  244. \n
  245. \n
  246. \n
  247. \n
  248. \n
  249. \n
  250. \n
  251. \n
  252. \n
  253. \n
  254. \n
  255. \n
  256. \n
  257. \n
  258. \n
  259. \n
  260. \n
  261. \n
  262. \n
  263. \n
  264. \n
  265. \n
  266. \n
  267. \n
  268. \n
  269. \n
  270. \n
  271. \n
  272. \n
  273. \n
  274. \n
  275. \n
  276. \n
  277. \n
  278. \n
  279. \n
  280. \n
  281. \n
  282. \n
  283. \n
  284. \n
  285. \n
  286. \n
  287. \n
  288. \n
  289. \n
  290. \n
  291. \n