zoukankan      html  css  js  c++  java
  • netty笔记(一)--Demo

    Netty是一个Java开源框架,用于传输数据。由server和client组成,封装了Java nio,支持TCP, UDP等协议。这里写了一Demo

    EchoClientHandler.java
    package chapter1;
    
    import io.netty.buffer.ByteBuf;
    import io.netty.buffer.Unpooled;
    import io.netty.channel.ChannelHandler;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.SimpleChannelInboundHandler;
    import io.netty.util.CharsetUtil;
    
    @ChannelHandler.Sharable
    public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            ctx.writeAndFlush(Unpooled.copiedBuffer("hello guanxianseng", CharsetUtil.UTF_8));
        }
    
        protected void messageReceived(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
            System.out.println("Client received:" + msg.toString(CharsetUtil.UTF_8));
            System.out.println(msg.toString());
        }
    
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }
    
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println("Client received:" + msg.toString());
    
        }
    }
    EchoServer.java
    package chapter1;
    
    import io.netty.bootstrap.ServerBootstrap;
    import io.netty.channel.Channel;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.EventLoopGroup;
    import io.netty.channel.embedded.EmbeddedChannel;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.channel.socket.nio.NioServerSocketChannel;
    
    import java.net.InetSocketAddress;
    import java.util.concurrent.TimeUnit;
    
    public class EchoServer {
        private  int port = 1234;
    
        public EchoServer(int port) {
            this.port = port;
        }
    
        public static void main(String[] args) throws Exception{
            int port = 1234;
            EchoServer echoServer = new EchoServer(port);
            schedulTask();
            echoServer.start();
    
    
        }
    
        public void start() throws Exception{
            final EchoServerHandler serverHandler = new EchoServerHandler();
            EventLoopGroup group = new NioEventLoopGroup();
            try{
                ServerBootstrap b = new ServerBootstrap();
                b.group(group)
                        .channel(NioServerSocketChannel.class)
                        .localAddress(new InetSocketAddress(port))
                        .childHandler(new ChannelInitializer<SocketChannel>() {
                            protected void initChannel(SocketChannel ch) throws Exception {
                                ch.pipeline().addLast(serverHandler);
                            }
                        });
                ChannelFuture channelFuture = b.bind().sync();
                System.out.println("sync test1");
                channelFuture.channel().closeFuture().sync();
                System.out.println("sync test2");
    
            } catch (Exception e){
    
            }finally {
                group.shutdownGracefully().sync();
                System.out.println("sync test3");
            }
        }
    
        public static void schedulTask(){
            System.out.println("before test");
            Channel ch = new EmbeddedChannel();
            ch.eventLoop().scheduleAtFixedRate(new Runnable() {
                public void run() {
                    System.out.println("test");
                }
            }, 0, 5, TimeUnit.SECONDS);
        }
    }
    EchoClientHandler.java
    package chapter1;
    
    import io.netty.buffer.ByteBuf;
    import io.netty.buffer.Unpooled;
    import io.netty.channel.ChannelHandler;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.SimpleChannelInboundHandler;
    import io.netty.util.CharsetUtil;
    
    @ChannelHandler.Sharable
    public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            ctx.writeAndFlush(Unpooled.copiedBuffer("hello guanxianseng", CharsetUtil.UTF_8));
        }
    
        protected void messageReceived(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
            System.out.println("Client received:" + msg.toString(CharsetUtil.UTF_8));
            System.out.println(msg.toString());
        }
    
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }
    
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println("Client received:" + msg.toString());
    
        }
    }
    EchoClient.java
    package chapter1;
    
    import io.netty.bootstrap.Bootstrap;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.EventLoopGroup;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.channel.socket.nio.NioSocketChannel;
    
    import java.net.InetSocketAddress;
    
    public class EchoClient {
        private String host;
        private int port;
    
        public EchoClient(String host, int port) {
            this.host = host;
            this.port = port;
        }
    
        public static void main(String[] args) throws Exception {
            int port = 1234;
            String host = "127.0.0.1";
            EchoClient echoClient = new EchoClient(host, port);
            echoClient.start();
        }
    
    
        public void start() throws Exception{
            EventLoopGroup group = new NioEventLoopGroup();
            try{
                Bootstrap b = new Bootstrap();
                b.group(group)
                        .channel(NioSocketChannel.class)
                        .remoteAddress(new InetSocketAddress(host, port))
                        .handler(new ChannelInitializer<SocketChannel>() {
                            protected void initChannel(SocketChannel ch) throws Exception {
                                ch.pipeline().addLast(new EchoClientHandler());
                            }
                        });
                ChannelFuture f = b.connect().sync();
                f.channel().closeFuture().sync();
    
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                group.shutdownGracefully().sync();
            }
        }
    }

    netty如何实现各种回调,怎么发送、接收消息,还要看下源码

  • 相关阅读:
    mysql存储过程 --游标的使用 取每行记录 (多字段)
    mysql rowid实现
    redis进程守护脚本
    CF1042B 【Vitamins】(去重,状压搜索)
    CF1042A 【Benches】(优先队列)
    魔板 Magic Squares(广搜,状态转化)
    解方程(hash,秦九韶算法)
    noip模拟赛 动态仙人掌(并查集,贪心)
    (暴力碾标算)NOIP模拟赛 宗教仪式
    牛客网NOIP赛前集训营-提高组18/9/9 A-中位数
  • 原文地址:https://www.cnblogs.com/luckygxf/p/9226015.html
Copyright © 2011-2022 走看看