您的位置:首页 > 编程语言 > Java开发

Netty4学习笔记-002

2014-04-07 22:51 555 查看
Blocking IO:

 

public
class
PlainEchoServer {
 
   publicvoidserve(intport)
throwsIOException {
        final
ServerSocket socket = new
ServerSocket(port);
        try {
            while (true) {
                final Socket clientSocket = socket.accept();
                System.out.println("Accepted connection from " + clientSocket);
 
                new Thread(new Runnable() {
                    @Override
                    public
void
run() {
                        try {
 
                            BufferedReaderreader = newBufferedReader(
                                    newInputStreamReader(clientSocket.getInputStream()));
                            PrintWriter writer= newPrintWriter(clientSocket
                                   .getOutputStream(), true);
                            [b]while
(true) {
                               writer.println(reader.readLine());
                                writer.flush();
                            }
 
                        } catch (IOException e) {
                           e.printStackTrace();
                            try {
                                clientSocket.close();
                            } catch (IOException ex) {
                                // ignore on close
                            }
                        }
                    }
                }).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
   }
}

 

Non-blocking IO:

 
public
class
PlainNioEchoServer {
 
   publicvoidserve(intport)
throwsIOException {
        System.out.println("Listening for connections on port "+ port);
        ServerSocketChannel serverChannel;
        Selector selector;
 
        serverChannel = ServerSocketChannel.open();
        ServerSocket ss = serverChannel.socket();
        InetSocketAddress address = newInetSocketAddress(port);
        ss.bind(address);
        serverChannel.configureBlocking(false);
        selector = Selector.open();
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);
 
 
        while (true) {
 
            try {
                selector.select();
            } catch (IOException ex) {
                ex.printStackTrace();
                // handle in a proper way
                break;
            }
 
            Set readyKeys =selector.selectedKeys();
            Iterator iterator =readyKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key =(SelectionKey) iterator.next();
                iterator.remove();
                try {
                    if (key.isAcceptable()) {
                        ServerSocketChannel server= (ServerSocketChannel) key.channel();
                        SocketChannel client =server.accept();
                        System.out.println("Accepted connection from " + client);
                       client.configureBlocking(false);
                        client.register(selector,SelectionKey.OP_WRITE | SelectionKey.OP_READ, ByteBuffer.allocate(100));
                    }
                    if (key.isReadable()) {
                        SocketChannel client =(SocketChannel) key.channel();
                        ByteBuffer output =(ByteBuffer) key.attachment();
                        client.read(output);
                    }
                    if (key.isWritable()) {
                        SocketChannel client =(SocketChannel) key.channel();
                        ByteBuffer output =(ByteBuffer) key.attachment();
                        output.flip();
                        client.write(output);
                        output.compact();
                    }
                } catch (IOException ex) {
                    key.cancel();
                    try {
                        key.channel().close();
                    } catch (IOException cex) {
                    }
                }
            }
        }
   }
}

 

使用Java7以后才有的NIO2

 

public
class
PlainNio2EchoServer {
 
   publicvoidserve(intport)
throwsIOException {
        System.out.println("Listening for connections on port "+ port);
        final AsynchronousServerSocketChannelserverChannel = AsynchronousServerSocketChannel.open();
        InetSocketAddress address = newInetSocketAddress(port);
        serverChannel.bind(address);
        final CountDownLatch
latch = new CountDownLatch(1);
       serverChannel.accept(null,
newCompletionHandler<AsynchronousSocketChannel, Object>() {
            @Override
            public
void
completed(final AsynchronousSocketChannel channel, Objectattachment) {
                serverChannel.accept(null,
this);
                ByteBuffer buffer = ByteBuffer.allocate(100);
                channel.read(buffer, buffer, newEchoCompletionHandler(channel));
            }
 
            @Override
            public
void
failed(Throwable throwable, Objectattachment) {
                try {
                    serverChannel.close();
                } catch (IOException e) {
                    // ingnore on close
                } finally {
                    latch.countDown();
                }
            }
        });
        try {
            latch.await();
        } catch (InterruptedException e) {
          Thread.currentThread().interrupt();
        }
 
   }
 
   privatefinalclassEchoCompletionHandler
implements CompletionHandler<Integer, ByteBuffer> {
        private
final
AsynchronousSocketChannel channel;
       EchoCompletionHandler(AsynchronousSocketChannel channel) {
            this.channel = channel;
        }
 
        @Override
        public
void
completed(Integer result, ByteBuffer buffer){
            buffer.flip();
            channel.write(buffer, buffer,
newCompletionHandler<Integer, ByteBuffer>() {
                @Override
                public
void
completed(Integer result, ByteBuffer buffer){
                    if (buffer.hasRemaining()) {
                        channel.write(buffer, buffer,
this);
                    } else {
                        buffer.compact();
                        channel.read(buffer, buffer,EchoCompletionHandler.this);
                    }
                }
 
                @Override
                public
void
failed(Throwable exc, ByteBuffer attachment){
                    try {
                        channel.close();
                    } catch (IOException e) {
                        // ingnore on close
                    }
                }
            });
        }
 
        @Override
        public
void
failed(Throwable exc, ByteBuffer attachment){
            try {
                channel.close();
            } [b]catch (IOException e) {
                // ingnore on close
            }
        }
   }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java Netty