zoukankan      html  css  js  c++  java
  • netty例子-客户端每隔5秒发送查询时间的请求,服务器端响应请求

    netty是jboss公司开发的,基于异步的、事件驱动的网络应用程序框架,快速开发高性能、高可靠性的服务器和客户端程序

    public class TimeServer {
        private int port=8080;
        public void run() throws Exception {
            EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
            EventLoopGroup workerGroup = new NioEventLoopGroup();
            try {
                ServerBootstrap b = new ServerBootstrap(); // (2)
                b.group(bossGroup, workerGroup)
                        .channel(NioServerSocketChannel.class) // (3)
                        .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
                            @Override
                            public void initChannel(SocketChannel ch) throws Exception {
                                ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
                                ch.pipeline().addLast(new StringDecoder());
                                ch.pipeline().addLast(new TimeServerHandler());
                            }
                        });
                ChannelFuture f = b.bind(port).sync(); // (5)
                System.out.println("TimeServer Started on 8080...");
                f.channel().closeFuture().sync();
            } finally {
                workerGroup.shutdownGracefully();
                bossGroup.shutdownGracefully();
            }
        }
        public static void main(String[] args) throws Exception {
            new TimeServer().run();
        }
    }
    public class TimeServerHandler extends ChannelInboundHandlerAdapter {
       @Override
       public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // 1
          String request = (String) msg; //2
          String response = null;
          if ("QUERY TIME ORDER".equals(request)) { // 3
             response = new Date(System.currentTimeMillis()).toString();
          } else {
             response = "BAD REQUEST";
          }
          response = response + System.getProperty("line.separator"); // 4
          ByteBuf resp = Unpooled.copiedBuffer(response.getBytes()); // 5
          ctx.writeAndFlush(resp); // 6
       }
    }
    public class TimeClient {
        public static void main(String[] args) throws Exception {
            String host = "localhost";
            int port = 8080;
            EventLoopGroup workerGroup = new NioEventLoopGroup();
            try {
                Bootstrap b = new Bootstrap(); // (1)
                b.group(workerGroup); // (2)
                b.channel(NioSocketChannel.class); // (3)
                b.handler(new ChannelInitializer<SocketChannel>() {// (4)
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new TimeClientHandler());
                    }
                });
                // Start the client.
                ChannelFuture f = b.connect(host, port).sync(); // (5)
                // Wait until the connection is closed.
                f.channel().closeFuture().sync();
            } finally {
                workerGroup.shutdownGracefully();
            }
        }
    }
    public class TimeClientHandler extends ChannelInboundHandlerAdapter {
        private byte[] req = ("QUERY TIME ORDER" + System.getProperty("line.separator")).getBytes();
    
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws InterruptedException {// 1
            sendMsg(ctx);
        }
    
        public void sendMsg(ChannelHandlerContext ctx) {
            Executors.newSingleThreadExecutor().submit(new MsgRunnable(ctx));
        }
    
        class MsgRunnable implements Runnable {
            ChannelHandlerContext ctx;
    
            MsgRunnable(ChannelHandlerContext ctx) {
                this.ctx = ctx;
            }
    
            @Override
            public void run() {
                while (true) {
                    ByteBuf message = Unpooled.buffer(req.length);
                    message.writeBytes(req);
                    ctx.writeAndFlush(message);
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
    
                }
    
            }
        }
    
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            String body = (String) msg;
            System.out.println("Now is:" + body);
        }
    }
  • 相关阅读:
    C语言学习笔记之 程序流程结构
    C语言学习笔记之 类型转换
    C语言学习笔记之 标准输入输出函数
    C语言学习笔记之 运算符
    bzoj 4322 东西分配问题
    bzoj 3240 矩阵乘法+十进制快速幂
    bzoj 4017 子序列和的异或以及异或的和
    bzoj 1934 最小割
    bzoj 3275 最小割
    bzoj 3931 最短路+最大流
  • 原文地址:https://www.cnblogs.com/moris5013/p/11358602.html
Copyright © 2011-2022 走看看