netty 实现http

java 复制代码
package cn.rainwer.nettywebsocket.Server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.HttpServerExpectContinueHandler;

public class NettyHttpServer {
    public static void main(String[] args) {

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ChannelFuture f = null;
        try {
            //ServerBootstrap负责初始化netty服务器,并且开始监听端口的socket请求
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            // 为监听客户端read/write事件的Channel添加用户自定义的ChannelHandler
                            socketChannel.pipeline()
//                                    .addLast("decoder", new HttpRequestDecoder())
//                                    .addLast("encoder", new HttpResponseEncoder())
                                    .addLast(new HttpServerCodec())
                                    .addLast(new HttpServerExpectContinueHandler())
                                    .addLast("aggregator", new HttpObjectAggregator(512 * 1024))
                                    .addLast(new NettyWebSocketConnectHandler2());
                        }
                    });
            f = b.bind(9996).sync();
            System.out.println("======NettyServer启动成功!!!=========");
            // f.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (f != null && f.isSuccess()) {
                System.out.println("Netty server listening on port " + " and ready for connections...");
            } else {
                System.out.println("Netty server start up Error!");
            }
        }
    }
}
java 复制代码
package cn.rainwer.nettywebsocket.Server;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.nio.charset.StandardCharsets;

@Slf4j
@ChannelHandler.Sharable
@Component
public class NettyWebSocketConnectHandler2 extends SimpleChannelInboundHandler<Object> {

    @Override
    public void channelRead(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {
            log.info("准备提取token");
            //转化为http请求
            FullHttpRequest request = (FullHttpRequest) msg;
            //拿到请求地址
            String uri = request.uri();
            System.out.println(uri);
            //判断是不是websocket请求,如果是拿出我们传递的参数(我的是token)
            channelHandlerContext.channel().writeAndFlush("Welcome to " + InetAddress.getLocalHost().getHostName() + " service!\n");
            FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(request.protocolVersion(), HttpResponseStatus.OK, Unpooled.wrappedBuffer(uri.getBytes(StandardCharsets.UTF_8)));
            fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN)
                    .set(HttpHeaderNames.CONTENT_LENGTH, fullHttpResponse.content().readableBytes());
            channelHandlerContext.writeAndFlush(fullHttpResponse);
        } else {
        }
    }
}
相关推荐
救救孩子把39 分钟前
MCP本地高效与云端实时:stdio 与 HTTP+SSE 传输机制深度对比
网络·网络协议·http·sse·mcp·stdio
2501_915909061 小时前
我用 Appuploader绕过 Mac,成功把 iOS 应用上线了 App Store
websocket·网络协议·tcp/ip·http·网络安全·https·udp
hao_wujing1 小时前
衡量 5G 和未来网络的安全性
网络·5g
哞哞不熬夜2 小时前
JavaEE--初识网络
java·网络·java-ee
什么半岛铁盒2 小时前
Linux信号的保存
linux·运维·网络
百锦再2 小时前
大数据技术的主要方向及其应用详解
大数据·linux·网络·python·django·pygame
Think Spatial 空间思维4 小时前
【HTTPS基础概念与原理】对称加密与非对称加密在HTTPS中的协作
网络协议·http·https
小疆智控5 小时前
数字化工厂升级引擎:Modbus TCP转Profinet网关助力打造柔性生产系统
服务器·网络·tcp/ip
DourPanda6 小时前
polarctf-web-[rce1]
linux·网络协议·网络安全
purrrew6 小时前
【Java ee初阶】IP协议
服务器·网络协议·tcp/ip