zoukankan      html  css  js  c++  java
  • Netty4.X 学习(一)

    Server:

    import io.netty.buffer.ByteBuf;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.ChannelInboundHandlerAdapter;
    import io.netty.util.CharsetUtil;
    import io.netty.util.ReferenceCountUtil;
    
    import com.netty.utils.*;
    
    public class HelloServerHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            Log.logInfo(">>>>>> I'm server.");
            // System.out.println(">>>>>> I'm server.");
            String msg = "Hello world
    ";
            ByteBuf encoded = ctx.alloc().buffer(msg.length());
            encoded.writeBytes(msg.getBytes());
            ctx.write(encoded);
            ctx.flush();
        }
    
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg)
                throws Exception {
            //Log.logInfo("server receive message:" + msg);
            // System.out.println("服务器收到的消息:" + msg);
            ByteBuf in = (ByteBuf) msg;
            try {
                if (in.isReadable()) { // (1)
                    String str = in.toString(CharsetUtil.US_ASCII);
                    Log.logInfo("server receive message:" + str);
                }
            } finally {
                ReferenceCountUtil.release(msg); // (2)
            }
    
        }
    }
    package com.netty.example.PrintHello;
    
    import io.netty.bootstrap.ServerBootstrap;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.ChannelOption;
    import io.netty.channel.EventLoopGroup;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.channel.socket.nio.NioServerSocketChannel;
    
    public class HelloWorldServer {
        public static void main(String[] args) {
            //EventLoop 代替原来的 ChannelFactory
            EventLoopGroup bossGroup = new NioEventLoopGroup();
            EventLoopGroup workerGroup = new NioEventLoopGroup();
            try {
                ServerBootstrap serverBootstrap = new ServerBootstrap();
                // server端采用简洁的连写方式,client端才用分段普通写法。
                serverBootstrap.group(bossGroup, workerGroup)
                        .channel(NioServerSocketChannel.class)
                        .childHandler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            public void initChannel(SocketChannel ch)
                                    throws Exception {
                                ch.pipeline().addLast(new HelloServerHandler());
                            }
                        }).option(ChannelOption.SO_KEEPALIVE, true);
    
                ChannelFuture f = serverBootstrap.bind(8000).sync();
                f.channel().closeFuture().sync();
                System.out.println("TCP服务器已启动");
            } catch (InterruptedException e) {
            } finally {
                workerGroup.shutdownGracefully();
                bossGroup.shutdownGracefully();
            }
        }
    }

    运行后可以在终端直接通过telnet命令连接:

    telnet localhost 8000

    client:

    package com.netty.example.PrintHello;
    import io.netty.buffer.ByteBuf;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.ChannelInboundHandlerAdapter;
    import io.netty.util.ReferenceCountUtil;
    
    public class HelloClientHandler  extends ChannelInboundHandlerAdapter{
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println(">>>>> I'm client.");
    //        ctx.write("Hello world!");
    //        ctx.flush();
            String msg = "Are you ok?";  
            ByteBuf encoded = ctx.alloc().buffer(msg.length());  
            encoded.writeBytes(msg.getBytes());  
            ctx.write(encoded);  
            ctx.flush(); 
        }
        
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg)  throws Exception{
            ByteBuf in = (ByteBuf) msg;
            try {
                while (in.isReadable()) { // (1)
                    System.out.println("client收到服务器的消息:" + msg);
                    System.out.print((char) in.readByte());
                    System.out.flush();
                }
            } finally {
                ReferenceCountUtil.release(msg); // (2)
            }
        }
    }
    package com.netty.example.PrintHello;
    
    import java.net.InetSocketAddress;
    
    import io.netty.bootstrap.Bootstrap;
    import io.netty.bootstrap.ServerBootstrap;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.ChannelInboundHandlerAdapter;
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.ChannelOption;
    import io.netty.channel.EventLoopGroup;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.channel.socket.nio.NioServerSocketChannel;
    import io.netty.channel.socket.nio.NioSocketChannel;
    
    public class HelloWorldClient {
        public static void main(String[] args) {
            // Client服务启动器 3.x的ClientBootstrap 改为Bootstrap,且构造函数变化很大,这里用无参构造。
            Bootstrap bootstrap = new Bootstrap();
            // 指定channel类型
            bootstrap.channel(NioSocketChannel.class);
            // 指定Handler
            bootstrap.handler(new HelloClientHandler());
            // 指定EventLoopGroup
            bootstrap.group(new NioEventLoopGroup());
            // 连接到本地的8000端口的服务端
            bootstrap.connect(new InetSocketAddress("127.0.0.1", 8000));
        }
    }
  • 相关阅读:
    C# 字段 属性 方法 三霸主齐上阵
    C# 项目之总结,浓缩才是精华
    C# 语法 重中之重
    岁月流逝,C#成为我们IT精英永恒不变的经典
    pv:快餐厅4类职员正确并发运行的程序——用pv实现有向图的前驱关系哦!
    pv错题:用pv操作实现旅客,汽车之间的同步关系——北航2018考研计算机!!!!!!!!我还很不熟练,奋斗吧少年!!!!!!
    windows 的 DMA
    pv打卡:生产者消费者问题扩展——>南航2002pv习题哦
    冷门的OS知识:中断——这个我多大熟练qwq!
    Unix混合索引结构_文件系统_文件的组织_文件的物理结构_多级索引文件——>相关的小计算题!!!!!!重点重点重点!!!!!!
  • 原文地址:https://www.cnblogs.com/csu_xajy/p/3845266.html
Copyright © 2011-2022 走看看