需要导入的依赖
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.68.Final</version>
</dependency>
废话不多说,上代码
@Slf4j
public class Netty {
public static void run(String ip, Integer port) {
//设置一个线程组,用于接受请求
NioEventLoopGroup portGroup = new NioEventLoopGroup(1);
//设置一个线程组,用户处理接受到的请求
NioEventLoopGroup workGroup = new NioEventLoopGroup(8);
//创建一个serverBootstrap配置Netty服务器
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(portGroup, workGroup)//指定主从线程
.channel(NioServerSocketChannel.class)//指定NIO
.option(ChannelOption.SO_BACKLOG, 1024)//设置套接字的最大来凝结数
.childOption(ChannelOption.SO_KEEPALIVE, true)//设置长连接
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline() //设置处理器
.addLast(new HttpServerCodec())//设置编码
.addLast(new HttpObjectAggregator(99 * 1024 * 1024))
.addLast(new HttpServerExpectContinueHandler())
.addLast(new ChunkedWriteHandler())//处理大量写请求
.addLast(new MyHttpServerHandler());//请求处理器
}
});
try {
//绑定ip端口启动Netty服务器
ChannelFuture sync = serverBootstrap.bind(ip, port).sync();
log.info("Netty服务开启...ip:" + ip + " 端口:" + ip);//这个自己设置
//等待服务器关闭
sync.channel().closeFuture().sync();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
//优雅的关闭
portGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
public static void main(String[] args) {
run("127.0.0.1",12222);
}
}
然后写处理器
class MyHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {
if (httpObject instanceof HttpRequest) {
//获取HttpRequest
HttpRequest httpRequest = (HttpRequest) httpObject;
URI uri = new URI(httpRequest.uri());
if ("/favicon.ico".equals(uri.getPath())) {
System.out.println("favicon.ico路径被过滤");
return;
}
System.out.println("访问url" + httpRequest.getUri().toString());
System.out.println("客户端地址" + channelHandlerContext.channel().remoteAddress());
//设置一个为utf8的字节数组
ByteBuf content = Unpooled.copiedBuffer("hello netty", CharsetUtil.UTF_8);
//创建一个http的响应
DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json");
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
//返回设置好的response
channelHandlerContext.writeAndFlush(response);
}
}
}
这样就完成了