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 {
        }
    }
}
相关推荐
小翼不想投降1 小时前
安全见闻全解析
网络·安全·web安全
Yan-英杰1 小时前
利用代理IP爬取Zillow房产数据用于数据分析
网络·python·网络协议·tcp/ip·数据分析
期待未来的男孩2 小时前
SEC_ASA 第二天作业
网络·windows·智能路由器
御风@户外2 小时前
学习笔记:从ncsi/nc-si协议和代码了解网络协议的设计范式
网络协议·ncsi
EQUINOX13 小时前
三、传输层,《计算机网络(自顶向下方法 第7版,James F.Kurose,Keith W.Ross)》
网络·计算机网络
drebander3 小时前
手撕 HttpClient:自己实现简单的 HTTP 请求工具
java·网络
冰红茶兑滴水4 小时前
HTTP 协议
linux·网络·c++·网络协议·http
悟空非空也4 小时前
完美解决 error: RPC failed; HTTP 400 curl 56 The requested URL returned error: 400
网络协议·http·rpc
nongcunqq4 小时前
不能通过 ip 直接访问 共享盘 解决方法
网络·网络协议·tcp/ip