如何再本地搭建一个简单的Netty服务器

需要导入的依赖

<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.68.Final</version>
</dependency>

废话不多说,上代码

@Slf4j
public class Netty {
    public static void run(String ip, Integer port) {
        //设置一个线程组,用于接受请求
        NioEventLoopGroup portGroup = new NioEventLoopGroup(1);
        //设置一个线程组,用户处理接受到的请求
        NioEventLoopGroup workGroup = new NioEventLoopGroup(8);
        //创建一个serverBootstrap配置Netty服务器
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(portGroup, workGroup)//指定主从线程
                .channel(NioServerSocketChannel.class)//指定NIO
                .option(ChannelOption.SO_BACKLOG, 1024)//设置套接字的最大来凝结数
                .childOption(ChannelOption.SO_KEEPALIVE, true)//设置长连接
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline() //设置处理器
                                .addLast(new HttpServerCodec())//设置编码
                                .addLast(new HttpObjectAggregator(99 * 1024 * 1024))
                                .addLast(new HttpServerExpectContinueHandler())
                                .addLast(new ChunkedWriteHandler())//处理大量写请求
                                .addLast(new MyHttpServerHandler());//请求处理器
                    }
                });
        try {
            //绑定ip端口启动Netty服务器
            ChannelFuture sync = serverBootstrap.bind(ip, port).sync();
            log.info("Netty服务开启...ip:" + ip + " 端口:" + ip);//这个自己设置
            //等待服务器关闭
            sync.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //优雅的关闭
            portGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        run("127.0.0.1",12222);
    }
}

然后写处理器 

class MyHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {
        if (httpObject instanceof HttpRequest) {
            //获取HttpRequest
            HttpRequest httpRequest = (HttpRequest) httpObject;
            URI uri = new URI(httpRequest.uri());
            if ("/favicon.ico".equals(uri.getPath())) {
                System.out.println("favicon.ico路径被过滤");
                return;
            }
            System.out.println("访问url" + httpRequest.getUri().toString());
            System.out.println("客户端地址" + channelHandlerContext.channel().remoteAddress());
            //设置一个为utf8的字节数组
            ByteBuf content = Unpooled.copiedBuffer("hello netty", CharsetUtil.UTF_8);
            //创建一个http的响应
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
            //返回设置好的response
            channelHandlerContext.writeAndFlush(response);
        }
    }
}

 这样就完成了

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大白猫~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值