日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

基于netty构建http服务器

發(fā)布時間:2023/12/10 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 基于netty构建http服务器 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

基于netty構(gòu)建http服務(wù)器

基于Netty構(gòu)建Http服務(wù)的流程如下:

  • Client向Server發(fā)送http請求。
  • Server端對http請求進(jìn)行解析。
  • Server端向Client發(fā)送http響應(yīng)。
  • Client對http響應(yīng)進(jìn)行解析。
  • 流程圖如下:

    服務(wù)器端實現(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()); // 請求消息解碼器ch.pipeline().addLast(new HttpObjectAggregator(65536));// 目的是將多個消息轉(zhuǎn)換為單一的request或者response對象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ù)器啟動,網(wǎng)址是 : " + "http://127.0.0.1:" + port);future.channel().closeFuture().sync();} finally {bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}} }

    在瀏覽器輸入http://127.0.0.1:8899就可以看到頁面顯示hello world。

    客戶端實現(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()); // 請求編碼器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請求request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);request.headers().set(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes());// 發(fā)送http請求ctx.writeAndFlush(request);}});}});// 啟動 server.ChannelFuture f = b.connect("127.0.0.1", 8899).sync();// 等待socket關(guān)閉f.channel().closeFuture().sync();} finally {workerGroup.shutdownGracefully();}} }

    總結(jié)

    以上是生活随笔為你收集整理的基于netty构建http服务器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。