Netty复习:(1)Http server: hello world

一、加依赖

复制代码
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.72.Final</version>
        </dependency>

二、创建自定义的handler

复制代码
package cn.edu.tju.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandler;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

import java.nio.ByteBuffer;

public class MyHttpHandler extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject httpObject) throws Exception {
        System.out.println("get info from client...");
        String message = "hello, world";
        ByteBuf byteBuf = Unpooled.copiedBuffer(message.getBytes());
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK, byteBuf);
        response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, message.length() );
        ctx.channel().writeAndFlush(response);
    }
}

三、定义启动类,在pipeline中添加自定义的handler

复制代码
package cn.edu.tju;


import cn.edu.tju.handler.MyHttpHandler;
import io.netty.bootstrap.ServerBootstrap;

import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;

public class NettyHttpServer {
    private static int port = 9093;
    public static void main(String[] args) {
        EventLoopGroup bossGroup=new NioEventLoopGroup();
        EventLoopGroup workerGroup=new NioEventLoopGroup();
        try{
            ServerBootstrap serverBootstrap=new ServerBootstrap();
            serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            channel.pipeline().addLast("httpServerCodec", new HttpServerCodec());
                            channel.pipeline().addLast("myHttpHandler", new MyHttpHandler());
                        }
                    });
            ChannelFuture channelFuture=serverBootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();




        }catch (Exception ex){

        }

    }
}
相关推荐
Zguigo11 分钟前
lesson43-44深入理解 TCP 可靠传输与流量控制:从机制到实战
网络·网络协议·tcp/ip
ai产品老杨20 分钟前
视频分析网络穿透项目实战记录:内网摄像头远程调试与跨网接入手册
网络·音视频
河北之花33 分钟前
计算机三级:路由器选型
网络·计算机网络·智能路由器
不可求~1 小时前
调用 GPT、Claude、Gemini API 报错怎么办:一套通用排查清单
网络·chrome·gpt
XR1234567881 小时前
高校AI智算中心网络:RoCE优化与一体化交付怎么选
网络·人工智能
gwf2161 小时前
RDMA迈向400G/800G:超宽带网络的技术挑战与突破 —— 从芯片架构到RTL实现的深度解析
网络·rdma·dpu·高性能网络·800g·智能网卡·rtl验证
2601_965798472 小时前
Evently Theme Setup Guide: Fast Conference, Meetup & Summit Architecture
服务器·网络·数据库
草莓熊Lotso2 小时前
【Redis 初阶】Hash 类型深度解析:结构化数据存储的最优解
linux·网络·数据库·redis·tcp/ip·缓存·哈希算法
caimouse2 小时前
ReactOS 窗口系统分析(31):TextOutW 文本输出全链路 — 从用户函数到显示缓冲区的旅程
网络·人工智能·计算机视觉
无忧.芙桃3 小时前
Linux系统之网络基础概念
网络