目标
用netty框架实现一个可以http访问的服务端(只是一个小demo)。
一、创建maven项目
创建一个maven项目,如下图
注意查看目录结构是否争取,是否有pom.xml
二、引入netty依赖
在pom.xml中引入netty
<dependencies>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.42.Final</version>
</dependency>
</dependencies>
三、代码编写
共两个类HttpHelloWorldServerHandler和HttpHelloWordServer,代码如下:
HttpHelloWorldServerHandler类
package http;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
public class HttpHelloWorldServerHandler extends SimpleChannelInboundHandler<HttpObject> {
private static final byte[] content = "helloworld".getBytes();
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();//这个必须重写
}
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {
if (httpObject instanceof HttpRequest){
HttpRequest req = (HttpRequest) httpObject;//强转
FullHttpResponse response = new DefaultFullHttpResponse(req.protocolVersion(),
HttpResponseStatus.OK, Unpooled.wrappedBuffer(content));//获取request protocolVersion,创建response.
response.headers()
.set(HttpHeaderNames.CONTENT_TYPE,HttpHeaderValues.TEXT_PLAIN)
.setInt(HttpHeaderNames.CONTENT_LENGTH,response.content().readableBytes());//设置一些header信息
ChannelFuture f = channelHandlerContext.write(response);//写回去
}
}
}
HttpHelloWordServer类
package http;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.HttpServerExpectContinueHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
public class HttpHelloWordServer {
public static void main(String[] args) {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer() {
@Override
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new HttpServerCodec());
p.addLast(new HttpServerExpectContinueHandler());
p.addLast(new HttpHelloWorldServerHandler());
}
});
try {
Channel ch = b.bind(8080).sync().channel();//异步创建channel
ch.closeFuture().sync();//异步关闭
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
四、启动测试
1)启动HttpHelloWordServer的main方法。
2)访问localhost:8080,如下即为成功
参考:代码参考傅健老师极客时间专栏《Netty 源码剖析与实战》