• netty1


     

    tcp server端代码

     public static void main(String[] args) throws InterruptedException {
            NioEventLoopGroup workerGroup = new NioEventLoopGroup();
            NioEventLoopGroup bossGroup = new NioEventLoopGroup();
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,124) // 当服务器请求处理线程全满时,用于临时存放已完成三次握手的请求的队列的最大长度
                    .childOption(ChannelOption.SO_KEEPALIVE,true)// 对tcp连接进行心跳保活
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new NettyServerHandler());
                }
            });
            System.out.println("server start ok...");
            ChannelFuture channelFuture = bootstrap.bind(8881).sync();
            // 异步处理
            channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (channelFuture.isSuccess()){
                        System.out.println("监听端口 成功");
                    }else {
                        System.out.println("监听端口 失败");
                    }
                }
            });
            System.out.println("h");
            channelFuture.channel().closeFuture().sync();
    
    
        }

    serverhandler

    package com.rudy.netty;
    
    import io.netty.buffer.ByteBuf;
    import io.netty.buffer.Unpooled;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.ChannelInboundHandlerAdapter;
    import io.netty.util.CharsetUtil;
    
    public class NettyServerHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ByteBuf buf = (ByteBuf) msg;
            System.out.println("客户端说:"+buf.toString(CharsetUtil.UTF_8));
        }
    
        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            ctx.writeAndFlush(Unpooled.copiedBuffer("你好客户端",CharsetUtil.UTF_8));
        }
    
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }
    }

    client端代码

    package com.rudy.netty;
    
    import io.netty.bootstrap.Bootstrap;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.channel.socket.nio.NioSocketChannel;
    
    public class MyNettyClient {
        public static void main(String[] args) throws InterruptedException {
            NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
            Bootstrap bootStrap = new Bootstrap();
            bootStrap.group(eventExecutors)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new NettyClientHandler());
                        }
                    });
    
            ChannelFuture channelFuture = bootStrap.connect("127.0.0.1", 8881).sync();
            channelFuture.channel().closeFuture().sync();
    
    
        }
    }

    clienthandler

    package com.rudy.netty;
    
    import io.netty.buffer.ByteBuf;
    import io.netty.buffer.Unpooled;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.ChannelInboundHandlerAdapter;
    import io.netty.util.CharsetUtil;
    
    public class NettyClientHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            ctx.channel().writeAndFlush(Unpooled.copiedBuffer("这里是客户端", CharsetUtil.UTF_8));
    
        }
    
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ByteBuf buf = (ByteBuf) msg;
            System.out.println("服务器回复消息:"+buf.toString(CharsetUtil.UTF_8));
        }
    }

    在channel对eventloop任务队列 添加普通任务任务

    注意eventloop是个队列 任务是排队执行的

    ctx.channel().eventLoop().execute(new Runnable() {
                @Override
                public void run() {
                    ByteBuf buf = (ByteBuf) msg;
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("客户端说:"+buf.toString(CharsetUtil.UTF_8));
                }
            });

     定时提交任务

    ctx.channel().eventLoop().schedule(new Runnable() {
                @Override
                public void run() {
                    ctx.writeAndFlush(Unpooled.copiedBuffer("你好客户端2", CharsetUtil.UTF_8));
                }
            }, 2, TimeUnit.SECONDS);

    netty实现http服务

    // SimpleChannelInboundHandler 是 ChannelInboundHandlerAdapter子类
    // HttpObject 相互通信的数据被封装成httpobject
    // 每个http请求都会新创建pipeline和handler
    public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
            if (msg instanceof HttpRequest){
                System.out.println(msg.getClass());
                System.out.println(ctx.channel().remoteAddress());
                URI uri = new URI(((HttpRequest) msg).uri());
                if(uri.getPath().equals("/favicon.ico")){
                    System.out.println("拒绝请求");
                    return;
                }
                ByteBuf content = Unpooled.copiedBuffer("hello 我是服务器", CharsetUtil.UTF_8);
                DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,content);
                response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain; charset=utf-8");
                response.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());
                ctx.writeAndFlush(response);
            }
        }
    }
    public class NettyServerInitializer extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(new HttpServerCodec());
            pipeline.addLast(new HttpServerHandler());
        }
    }
     public static void main(String[] args) {
            NioEventLoopGroup bossGroup = new NioEventLoopGroup();
            NioEventLoopGroup workerGroup = new NioEventLoopGroup();
            try {
                ServerBootstrap serverBootstrap = new ServerBootstrap();
                serverBootstrap.group(bossGroup,workerGroup)
                        .channel(NioServerSocketChannel.class)
                        .childHandler(new NettyServerInitializer());
                ChannelFuture channelFuture = serverBootstrap.bind(8881).sync();
                channelFuture.channel().closeFuture().sync();
    
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        }
  • 相关阅读:
    神医,全部的诡异动画,
    显示界面的,调节frame的代码 写到 viewwillappear,
    两个像素,
    人类的心理行为模式,---》阮一峰,
    浅谈IE11--web开发测试
    node中的console
    node服务器重定向
    服务端渲染&&客户端渲染
    node积累
    Apache网页文件目录模板
  • 原文地址:https://www.cnblogs.com/isnotnull/p/15993981.html
Copyright © 2020-2023  润新知