实现效果:
1. Netty服务启动对特定端口如:8081进行监听
2. 在浏览器通过 http://localhost:8081/aaaa 发送请求,Netty服务可以进行相应响应到浏览器
1. 引入netty依赖
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.42.Final</version>
</dependency>
2. 定义NettyHttpServer类,实现Netty的服务监听
public class NettyHttpServer {
private int port;
public NettyHttpServer(int port) {
this.port = port;
}
public void run() throws InterruptedException {
EventLoopGroup bossGroup = null; // bossGroup 线程组
EventLoopGroup workerGroup = null;// workerGroup 线程组
try {
bossGroup = new NioEventLoopGroup(1); // bossGroup 线程组
workerGroup = new NioEventLoopGroup();// workerGroup 线程组
ServerBootstrap serverBootstrap = new ServerBootstrap(); // 服务端启动助手
serverBootstrap.group(bossGroup, workerGroup)
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel ch) throws Exception {// 创建通道初始化对象
// 向 pipeline 添加 HTTPServer编解码器
ch.pipeline().addLast(new HttpServerCodec());
// http 消息处理 handler
ch.pipeline().addLast(new NettyHttpServerHandler());
}
});
// 绑定端口
ChannelFuture channelFuture = serverBootstrap.bind(port);
channelFuture.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()){
System.out.println("端口监听成功~~~~~~~~~~");
}else {
System.out.println("端口监听失败~~~~~~~~~~");
}
}
});
channelFuture.channel().closeFuture().sync();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws InterruptedException {
new NettyHttpServer(8081).run();
}
}
3. 定义http请求处理类 NettyHttpServerHandler
public class NettyHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
if (msg instanceof HttpRequest){
DefaultHttpRequest httpRequest = (DefaultHttpRequest) msg;
String uri = httpRequest.uri(); // 浏览器请求路径
System.out.println(" 浏览器请求路径 " + uri);
ByteBuf result = Unpooled.copiedBuffer("我是netty服务器,刚才的请求是 :" + uri, CharsetUtil.UTF_8);
// 返回信息给浏览器 HttpVersion version, HttpResponseStatus status, ByteBuf content
DefaultFullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, result);
// 设置必要的头信息
httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/html;charset=utf-8");
httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, result.readableBytes());
ctx.writeAndFlush(httpResponse);
}
}
}
4. 验证 浏览器输入 http://localhost:8081/aaaa