实例:Netty 基于Http协议下的数据传输Demo

Http/Https协议是最重要最常用到的协议之一,Netty提供了一些了的Handler来处理Http协议下的编码工作。下面就介绍一个Netty实例:

1.通过HttpClient发送Protobuf类型数据到服务端

2.服务端Netty负责把接收到的Http请求中的数据再发送到客户端。

3.其中Netty对发送的数据量没有限制,因为Http发送的message往往是由一系列infragment构成,Netty可以把接收到的http请求片段信息整合(Aggregator)到一起,最终得到一个FullHttpRequest。


Client端:

  1. package NettyDemo.echo.client;  
  2.   
  3. import java.io.IOException;  
  4. import org.apache.http.HttpEntity;  
  5. import org.apache.http.HttpHost;  
  6. import org.apache.http.HttpResponse;  
  7. import org.apache.http.client.ClientProtocolException;  
  8. import org.apache.http.client.methods.HttpPost;  
  9. import org.apache.http.conn.params.ConnRoutePNames;  
  10. import org.apache.http.entity.ByteArrayEntity;  
  11. import org.apache.http.impl.client.DefaultHttpClient;  
  12. import NettyDemo.echo.protocal.AddressBookProtos;  
  13. import NettyDemo.echo.server.HttpProtobufServer;  
  14.   
  15. public class HttpClientDemo {  
  16.     public static void main(String[] args) throws ClientProtocolException,  
  17.             IOException {  
  18.         DefaultHttpClient httpclient = new DefaultHttpClient();  
  19.         HttpHost proxy = new HttpHost(HttpProtobufServer.IP,  
  20.                 HttpProtobufServer.PORT);  
  21.         httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,  
  22.                 proxy);  
  23.         HttpPost httppost = new HttpPost("");  
  24.         AddressBookProtos.AddressBook.Builder address = AddressBookProtos.AddressBook  
  25.                 .newBuilder();  
  26.         for (int i = 0; i < 20000; i++) {  
  27.             AddressBookProtos.Person.Builder person = AddressBookProtos.Person  
  28.                     .newBuilder();  
  29.             person.setName("HeavenWang");  
  30.             person.setId(i);  
  31.             person.setEmail("wanghouda@126.com");  
  32.             address.addPerson(person);  
  33.         }  
  34.         ByteArrayEntity entity = new ByteArrayEntity(address.build().toByteArray());  
  35.         httppost.setEntity(entity);  
  36.         HttpResponse response = httpclient.execute(httppost);  
  37.         HttpEntity receiveEntity = response.getEntity();  
  38.         System.out.println("----------------------------------------");  
  39.         System.out.println(response.getStatusLine());  
  40.         if (receiveEntity != null) {  
  41.             System.out.println("Response content length: " + receiveEntity.getContentLength());  
  42.         }  
  43.         System.out.println("success");  
  44.     }  
  45. }  

服务器端NettyService:


  1. <span style="font-size:12px;">package NettyDemo.echo.server;  
  2.   
  3. import io.netty.bootstrap.ServerBootstrap;  
  4. import io.netty.channel.ChannelInitializer;  
  5. import io.netty.channel.ChannelPipeline;  
  6. import io.netty.channel.EventLoopGroup;  
  7. import io.netty.channel.nio.NioEventLoopGroup;  
  8. import io.netty.channel.socket.SocketChannel;  
  9. import io.netty.channel.socket.nio.NioServerSocketChannel;  
  10. import io.netty.handler.codec.http.HttpObjectAggregator;  
  11. import io.netty.handler.codec.http.HttpRequestDecoder;  
  12. import io.netty.handler.codec.http.HttpResponseEncoder;  
  13. import io.netty.handler.codec.http.HttpServerCodec;  
  14. import NettyDemo.echo.handler.HttpProtobufServerHandler;  
  15.   
  16. public class HttpProtobufServer {  
  17.     public static final String IP = "127.0.0.1";  
  18.     public static final int PORT = 8080;  
  19.     //private static MessageLite lite=AddressBookProtos.AddressBook.getDefaultInstance();  
  20.     /**用于分配处理业务线程的线程组个数 */  
  21.     protected static final int BIZGROUPSIZE = Runtime.getRuntime().availableProcessors()*2//默认  
  22.     /** 业务出现线程大小*/  
  23.     protected static final int BIZTHREADSIZE = 4;  
  24.     private static final EventLoopGroup bossGroup = new NioEventLoopGroup(BIZGROUPSIZE);  
  25.     private static final EventLoopGroup workerGroup = new NioEventLoopGroup(BIZTHREADSIZE);  
  26.     protected static void run() throws Exception {  
  27.         ServerBootstrap b = new ServerBootstrap();  
  28.         b.group(bossGroup, workerGroup);  
  29.         b.channel(NioServerSocketChannel.class);  
  30.         b.childHandler(new ChannelInitializer<SocketChannel>() {  
  31.             @Override  
  32.             public void initChannel(SocketChannel ch) throws Exception {  
  33.                 ChannelPipeline pipeline = ch.pipeline();                 
  34.                 pipeline.addLast("decoder"new HttpRequestDecoder());  
  35.                 /**usually we receive http message infragment,if we want full http message, 
  36.                  * we should bundle HttpObjectAggregator and we can get FullHttpRequest。 
  37.                  * 我们通常接收到的是一个http片段,如果要想完整接受一次请求的所有数据,我们需要绑定HttpObjectAggregator,然后我们 
  38.                  * 就可以收到一个FullHttpRequest-是一个完整的请求信息。 
  39.                 **/  
  40.                 pipeline.addLast("servercodec",new HttpServerCodec());  
  41.                 pipeline.addLast("aggegator",new HttpObjectAggregator(1024*1024*64));//定义缓冲数据量  
  42.                 pipeline.addLast(new HttpProtobufServerHandler());  
  43.                 pipeline.addLast("responseencoder",new HttpResponseEncoder());  
  44.             }  
  45.         });  
  46.         b.bind(IP, PORT).sync();  
  47.         System.out.println("TCP服务器已启动");  
  48.     }  
  49.   
  50.     protected static void shutdown() {  
  51.         workerGroup.shutdownGracefully();  
  52.         bossGroup.shutdownGracefully();  
  53.     }  
  54.   
  55.     public static void main(String[] args) throws Exception {  
  56.         System.out.println("开始启动http服务器...");  
  57.         HttpProtobufServer.run();  
  58. //      TcpServer.shutdown();  
  59.     }  
  60. }  
  61. </span>  

Handler:

  1. package NettyDemo.echo.handler;  
  2.   
  3. import io.netty.channel.ChannelHandlerContext;  
  4. import io.netty.channel.SimpleChannelInboundHandler;  
  5. import io.netty.handler.codec.http.DefaultFullHttpRequest;  
  6. import io.netty.handler.codec.http.DefaultFullHttpResponse;  
  7. import io.netty.handler.codec.http.HttpResponseStatus;  
  8. import io.netty.handler.codec.http.HttpVersion;  
  9.   
  10. public class HttpProtobufServerHandler extends SimpleChannelInboundHandler<Object>{  
  11.     @Override  
  12.     protected void channelRead0(ChannelHandlerContext ctx,  Object msg) throws Exception {  
  13.         DefaultFullHttpRequest request=(DefaultFullHttpRequest)msg;  
  14.         DefaultFullHttpResponse response=new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.ACCEPTED, request.content());  
  15.         ctx.writeAndFlush(response);  
  16.     }  
  17.   
  18.       
  19. }  


附:FullHttpRequest构成,因此一个FullHttpRequest会包含请求message的所有片段。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值