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);
        }
    }
  • 相关阅读:
    适配者模式7(10)
    规范使用线程池与底层原理详解
    Java集合多线程安全
    CAS底层原理与ABA问题
    手写数字识别-小数据集
    深度学习-卷积
    Java并发编程volatile关键字
    朴素贝叶斯-垃圾邮件分类
    K均值算法
    mysql搭建主从复制(一主一从,双主双从)
  • 原文地址:https://www.cnblogs.com/moris5013/p/11358602.html
Copyright © 2011-2022 走看看