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 {
        }
    }
}
相关推荐
昊昊该干饭了2 小时前
玩转代理 IP :实战爬虫案例
运维·服务器·爬虫·网络协议·tcp/ip·网络爬虫
菌菌巧乐兹2 小时前
电脑知识 | TCP通俗易懂详解 <一>
服务器·网络·tcp/ip
无名之逆3 小时前
[特殊字符] 超轻高性能的 Rust HTTP 服务器 —— Hyperlane [特殊字符][特殊字符]
java·服务器·开发语言·前端·网络·http·rust
稳联技术4 小时前
玻璃厂退火炉“温度智囊”:Profinet转ModbusRTU网关
运维·服务器·网络
GZX墨痕4 小时前
从集线器到路由器:解码网络设备与ARP的通信密码
网络协议
小王努力学编程4 小时前
【Linux网络编程】UDP Echo Server的实现
linux·运维·服务器·网络·c++·学习·udp
独行侠1@tcl4 小时前
3.BGP路由黑洞
网络·智能路由器
Dklau-c5 小时前
『Linux_网络』 第一章 网络基础概念
linux·服务器·网络
开心呆哥6 小时前
【检测手机有无网络】
网络
清风~徐~来7 小时前
【Linux】网络层协议 IP
linux·网络·tcp/ip