zoukankan      html  css  js  c++  java
  • Netty

    高性能的网络应用程序框架(对底层进行封装)

    Java NIO框架
    典型的C/S架构
     
    Netty比Mina更容易学习,优先使用netty
     
    server:
     
    package me.hello.netty;
    
    import org.jboss.netty.bootstrap.ServerBootstrap;
    import org.jboss.netty.channel.*;
    import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
    import org.jboss.netty.handler.codec.string.StringDecoder;
    import org.jboss.netty.handler.codec.string.StringEncoder;
    
    import java.net.InetSocketAddress;
    import java.util.concurrent.Executors;
    
    /**
     * God Bless You!
     * Author: Fangniude
     * Date: 2013-07-15
     */
    public class NettyServer {
        public static void main(String[] args) {
            ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
    
            // Set up the default event pipeline.
            bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
                @Override
                public ChannelPipeline getPipeline() throws Exception {
                    return Channels.pipeline(new StringDecoder(), new StringEncoder(), new ServerHandler());
                }
            });
    
            // Bind and start to accept incoming connections.
            Channel bind = bootstrap.bind(new InetSocketAddress(8000));
            System.out.println("Server已经启动,监听端口: " + bind.getLocalAddress() + ", 等待客户端注册。。。");
        }
    
        private static class ServerHandler extends SimpleChannelHandler {
            @Override
            public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
                if (e.getMessage() instanceof String) {
                    String message = (String) e.getMessage();
                    System.out.println("Client发来:" + message);
    
                    e.getChannel().write("Server已收到刚发送的:" + message);
    
                    System.out.println("
    等待客户端输入。。。");
                }
    
                super.messageReceived(ctx, e);
            }
    
            @Override
            public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
                super.exceptionCaught(ctx, e);
            }
    
            @Override
            public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
                System.out.println("有一个客户端注册上来了。。。");
                System.out.println("Client:" + e.getChannel().getRemoteAddress());
                System.out.println("Server:" + e.getChannel().getLocalAddress());
                System.out.println("
    等待客户端输入。。。");
                super.channelConnected(ctx, e);
            }
        }
    }
    

      

    client:

    package me.hello.netty;
    
    import org.jboss.netty.bootstrap.ClientBootstrap;
    import org.jboss.netty.channel.*;
    import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
    import org.jboss.netty.handler.codec.string.StringDecoder;
    import org.jboss.netty.handler.codec.string.StringEncoder;
    
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.InetSocketAddress;
    import java.util.concurrent.Executors;
    
    /**
     * God Bless You!
     * Author: Fangniude
     * Date: 2013-07-15
     */
    public class NettyClient {
    
        public static void main(String[] args) {
            // Configure the client.
            ClientBootstrap bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
    
            // Set up the default event pipeline.
            bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
                @Override
                public ChannelPipeline getPipeline() throws Exception {
                    return Channels.pipeline(new StringDecoder(), new StringEncoder(), new ClientHandler());
                }
            });
    
            // Start the connection attempt.
            ChannelFuture future = bootstrap.connect(new InetSocketAddress("localhost", 8000));
    
            // Wait until the connection is closed or the connection attempt fails.
            future.getChannel().getCloseFuture().awaitUninterruptibly();
    
            // Shut down thread pools to exit.
            bootstrap.releaseExternalResources();
        }
    
        private static class ClientHandler extends SimpleChannelHandler {
            private BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
    
            @Override
            public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
                if (e.getMessage() instanceof String) {
                    String message = (String) e.getMessage();
                    System.out.println(message);
    
                    e.getChannel().write(sin.readLine());
    
                    System.out.println("
    等待客户端输入。。。");
                }
    
                super.messageReceived(ctx, e);
            }
    
            @Override
            public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
                System.out.println("已经与Server建立连接。。。。");
                System.out.println("
    请输入要发送的信息:");
                super.channelConnected(ctx, e);
    
                e.getChannel().write(sin.readLine());
            }
        }
    }
    

      

  • 相关阅读:
    安装pyamf碰到的问题及其解决方法^_^(原创)
    django建立模型的一些体会(原创)
    终于搞完第三个作业了~~
    django传递嵌套对象给flex前端的方法(原创)
    flex:在一个.as文件中调用另一个.as文件的public函数(原创)
    hdu(4339)树状数组+二分查找
    1504: ZZ的橱柜(长沙理工oj)
    zoj(2110)Tempter of the Bone(DFS+奇偶剪枝)
    hdu(4267)A Simple Problem with Integers(三维树状数组)
    [USACO 1.5.3]特殊的质数肋骨
  • 原文地址:https://www.cnblogs.com/lnas01/p/4490690.html
Copyright © 2011-2022 走看看