基于netty构建http服务器
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                基于netty构建http服务器
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.                        
                                基于netty構(gòu)建http服務(wù)器
基于Netty構(gòu)建Http服務(wù)的流程如下:
流程圖如下:
服務(wù)器端實(shí)現(xiàn)
package com.morris.netty.protocol.http;import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.*; 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.*; import io.netty.util.CharsetUtil; import lombok.extern.slf4j.Slf4j;import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE; import static io.netty.handler.codec.http.HttpResponseStatus.OK; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;@Slf4j public class Server {private static final int port = 8899;public static void main(String[] args) throws Exception {EventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup workerGroup = new NioEventLoopGroup();try {ServerBootstrap b = new ServerBootstrap();b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ch.pipeline().addLast(new HttpRequestDecoder()); // 請(qǐng)求消息解碼器ch.pipeline().addLast(new HttpObjectAggregator(65536));// 目的是將多個(gè)消息轉(zhuǎn)換為單一的request或者response對(duì)象ch.pipeline().addLast(new HttpResponseEncoder());//響應(yīng)編碼器ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {FullHttpRequest request = (FullHttpRequest) msg;log.info("method:{}", request.method().name());log.info("uri:{}", request.uri());log.info("content:{}", request.content().toString(CharsetUtil.UTF_8));FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");ByteBuf buffer = Unpooled.copiedBuffer("<h3>hello world</h3>", CharsetUtil.UTF_8);response.content().writeBytes(buffer);buffer.release();request.release();ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);}});// 業(yè)務(wù)邏輯}});ChannelFuture future = b.bind("127.0.0.1", port).sync();log.info("HTTP服務(wù)器啟動(dòng),網(wǎng)址是 : " + "http://127.0.0.1:" + port);future.channel().closeFuture().sync();} finally {bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}} }在瀏覽器輸入http://127.0.0.1:8899就可以看到頁(yè)面顯示hello world。
客戶端實(shí)現(xiàn)
package com.morris.netty.protocol.http;import io.netty.bootstrap.Bootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.http.*; import io.netty.util.CharsetUtil; import lombok.extern.slf4j.Slf4j;@Slf4j public class Client {public static void main(String[] args) throws InterruptedException {EventLoopGroup workerGroup = new NioEventLoopGroup();try {Bootstrap b = new Bootstrap();b.group(workerGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer() {@Overrideprotected void initChannel(Channel ch) throws Exception {ch.pipeline().addLast(new HttpResponseDecoder()); // 響應(yīng)解碼器ch.pipeline().addLast(new HttpObjectAggregator(65536));ch.pipeline().addLast(new HttpRequestEncoder()); // 請(qǐng)求編碼器ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {FullHttpResponse httpResponse = (FullHttpResponse)msg;log.info("status:{}", httpResponse.status());log.info("headers:{}", httpResponse.headers());log.info("body:{}", httpResponse.content().toString(CharsetUtil.UTF_8));httpResponse.release();}@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");// 構(gòu)建http請(qǐng)求request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);request.headers().set(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes());// 發(fā)送http請(qǐng)求ctx.writeAndFlush(request);}});}});// 啟動(dòng) server.ChannelFuture f = b.connect("127.0.0.1", 8899).sync();// 等待socket關(guān)閉f.channel().closeFuture().sync();} finally {workerGroup.shutdownGracefully();}} }總結(jié)
以上是生活随笔為你收集整理的基于netty构建http服务器的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: 前端学习(603):计算机基础
 - 下一篇: 前端学习(733):函数的参数