閱讀前請參考html
有了前兩篇的使用基礎,學習本文也很簡單!只須要在前兩文的基礎上稍微改動便可!java
<!-- Netty -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.22.Final</version>
</dependency>
關於啓動類,須要咱們作的就是自定義端口以及繼承ChannelInitializer類。web
/** * Netty服務器啓動 * Create by yster@foxmail.com 2018-05-04 **/
public class HttpServerStartup {
public void startup() {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workGroup);
b.channel(NioServerSocketChannel.class);
b.childHandler(new MyServerInitializer()); //繼承重寫類
Channel ch = b.bind(8888).sync().channel(); //自定義端口
ch.closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
//優雅的退出程序
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
}
/** * 信道初始化 * Create by yster@foxmail.com 2018-05-04 **/
public class MyServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
/** * http-request解碼器 * http服務器端對request解碼 */
pipeline.addLast("decoder", new HttpRequestDecoder());
/** * http-response解碼器 * http服務器端對response編碼 */
pipeline.addLast("encoder", new HttpResponseEncoder());
pipeline.addLast("deflater", new HttpContentCompressor());
pipeline.addLast("handler", new MyServerChannelHandler());
}
}
值得一提的是,上面信道的處理對post請求而言不太方便獲取參數。服務器
/** * 綁定處理程序中的簡單通道 * Create by yster@foxmail.com 2018-05-04 **/
@Sharable
public class MyServerChannelHandler extends SimpleChannelInboundHandler<HttpObject> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg){
if (msg instanceof HttpRequest) {
//request response都已經獲取到!
ByteBuf byteBuf = Unpooled.copiedBuffer("Hello".getBytes());
DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK,byteBuf);
ctx.channel().writeAndFlush(response);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ctx.channel().close();
cause.printStackTrace();
}
}