《Netty学习》(二)Hello World

来源:互联网 发布:怎么才能在淘宝上卖东西 编辑:程序博客网 时间:2024/05/29 13:07

1.创建maven工程并引入netty依赖

<dependency>            <groupId>io.netty</groupId>            <artifactId>netty-all</artifactId>            <version>4.1.6.Final</version></dependency>

2.创建服务器类 HttpServer

package james.gan;import java.net.InetAddress;import io.netty.bootstrap.ServerBootstrap;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelPipeline;import io.netty.channel.EventLoopGroup;import io.netty.channel.SimpleChannelInboundHandler;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioServerSocketChannel;import io.netty.handler.codec.DelimiterBasedFrameDecoder;import io.netty.handler.codec.Delimiters;import io.netty.handler.codec.string.StringDecoder;import io.netty.handler.codec.string.StringEncoder;/** * 服务端 * @author James */public class HttpServer {    /**     * 服务端监听的端口地址     */    private static final int portNumber = 7878;    public static void main(String[] args) throws InterruptedException {        // 监测客户端连接线程组        EventLoopGroup bossGroup = new NioEventLoopGroup();        // 工作线程组        EventLoopGroup workerGroup = new NioEventLoopGroup();        try {            //服务器对象            ServerBootstrap b = new ServerBootstrap();            b.group(bossGroup, workerGroup)                    // 使用NioServerSocketChannel通道                    .channel(NioServerSocketChannel.class)                    // Handler与Servlet中的filter很像,通过Handler可以完成通讯报文的解码编码、拦截指定的报文、                    // 统一对日志错误进行处理、统一对请求进行计数、控制Handler执行与否                    .childHandler(new HelloServerInitializer());            // 服务器绑定端口监听            ChannelFuture f = b.bind(portNumber).sync();            // 监听服务器关闭监听            f.channel().closeFuture().sync();            // 可以简写为            /* b.bind(portNumber).sync().channel().closeFuture().sync(); */        } finally {            // 关闭资源            bossGroup.shutdownGracefully();            workerGroup.shutdownGracefully();        }    }}/** * 为服务端通道预添加的inboundhandler * @author James */class HelloServerInitializer extends ChannelInitializer<SocketChannel> {    /**     * 当新客户端连接到本服务器时调用     */    @Override    protected void initChannel(SocketChannel ch) throws Exception {        //管线        ChannelPipeline pipeline = ch.pipeline();        // 以("\n")为结尾分割的 解码器        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));        // 字符串解码 和 编码        pipeline.addLast("decoder", new StringDecoder());        pipeline.addLast("encoder", new StringEncoder());        // 自己的逻辑Handler        pipeline.addLast("handler", new HelloServerHandler());    }}/** * 自身定义的处理器 * @author James */class HelloServerHandler extends SimpleChannelInboundHandler<String> {    /**     * 接收到客户端发送过来的数据时调用     */    @Override    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {        // 收到消息直接打印输出        System.out.println(ctx.channel().remoteAddress() + " Say : " + msg);        // 返回客户端消息 - 我已经接收到了你的消息        ctx.writeAndFlush("Received your message !\n");    }    /*     *      * 覆盖 channelActive 方法 在channel被启用的时候触发 (在建立连接的时候)     */    @Override    public void channelActive(ChannelHandlerContext ctx) throws Exception {        System.out.println("RamoteAddress : " + ctx.channel().remoteAddress() + " active !");        ctx.writeAndFlush("Welcome to " + InetAddress.getLocalHost().getHostName() + " service!\n");        super.channelActive(ctx);    }}

3.创建客户端类 HttpClient

package james.gan;import io.netty.bootstrap.Bootstrap;import io.netty.channel.Channel;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelPipeline;import io.netty.channel.EventLoopGroup;import io.netty.channel.SimpleChannelInboundHandler;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioSocketChannel;import io.netty.handler.codec.DelimiterBasedFrameDecoder;import io.netty.handler.codec.Delimiters;import io.netty.handler.codec.string.StringDecoder;import io.netty.handler.codec.string.StringEncoder;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;/** * 客户端类 * @author James */public class HelloClient {    /**服务器ip*/    public static String host = "127.0.0.1";    /**服务器端口号*/    public static int port = 7878;    public static void main(String[] args) throws InterruptedException, IOException {        EventLoopGroup group = new NioEventLoopGroup();        try {            //客户端            Bootstrap b = new Bootstrap();            b.group(group)            .channel(NioSocketChannel.class)//使用NioSocketChannel通道            .handler(new HelloClientInitializer());            // 连接服务端            Channel ch = b.connect(host, port).sync().channel();            // 控制台输入            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));            for (;;) {                String line = in.readLine();                if (line == null) {                    continue;                }                /*                 * 向服务端发送在控制台输入的文本 并用"\r\n"结尾                 * 之所以用\r\n结尾 是因为我们在handler中添加了 DelimiterBasedFrameDecoder 帧解码。                 * 这个解码器是一个根据\n符号位分隔符的解码器。所以每条消息的最后必须加上\n否则无法识别和解码                 * */                ch.writeAndFlush(line + "\r\n");            }        } finally {            // The connection is closed automatically on shutdown.关闭资源            group.shutdownGracefully();        }    }}class HelloClientInitializer extends ChannelInitializer<SocketChannel> {    @Override    protected void initChannel(SocketChannel ch) throws Exception {        ChannelPipeline pipeline = ch.pipeline();        /*         * 这个地方的 必须和服务端对应上。否则无法正常解码和编码         * 数据在网络中的传输编解码         * */        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));        pipeline.addLast("decoder", new StringDecoder());        pipeline.addLast("encoder", new StringEncoder());        // 客户端的逻辑        pipeline.addLast("handler", new HelloClientHandler());    }}/** * 自身处理器 * @author James */class HelloClientHandler extends SimpleChannelInboundHandler<String> {    /**     * 接收消息时调用的方法     */   @Override   protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {       System.out.println("Server say : " + msg);   }   /**    * 连接服务器时调用    */   @Override   public void channelActive(ChannelHandlerContext ctx) throws Exception {       System.out.println("Client active ");       super.channelActive(ctx);   }   /**    * 关闭连接时调用    */   @Override   public void channelInactive(ChannelHandlerContext ctx) throws Exception {       System.out.println("Client close ");       super.channelInactive(ctx);   }}

一个简单的Hello World就创建成功了,对使用现在应该有了一个大概的了解,下节我们会继续对Netty中重要的类进行学习。
wait…