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 {
        }
    }
}
相关推荐
DevSecOps选型指南2 小时前
2025软件供应链安全最佳实践︱证券DevSecOps下供应链与开源治理实践
网络·安全·web安全·开源·代码审计·软件供应链安全
利刃大大2 小时前
【在线五子棋对战】二、websocket && 服务器搭建
服务器·c++·websocket·网络协议·项目
国科安芯3 小时前
抗辐照MCU在卫星载荷电机控制器中的实践探索
网络·嵌入式硬件·硬件工程·智能硬件·空间计算
EasyDSS4 小时前
国标GB28181设备管理软件EasyGBS远程视频监控方案助力高效安全运营
网络·人工智能
玩转4G物联网4 小时前
零基础玩转物联网-串口转以太网模块如何快速实现与TCP服务器通信
服务器·网络·物联网·网络协议·tcp/ip·http·fs100p
派阿喵搞电子4 小时前
Ubuntu下有关UDP网络通信的指令
linux·服务器·网络
光芒Shine4 小时前
【物联网-ModBus-ASCII】
物联网·网络协议
hie988945 小时前
HTTP常见的请求方法、响应状态码、接口规范介绍
http
搬码临时工5 小时前
外网访问内网服务器常用的三种简单操作步骤方法,本地搭建网址轻松让公网连接
服务器·网络·智能路由器
帽儿山的枪手6 小时前
程序员必掌握的iptables五表五链
linux·网络协议