Netty4.0的DefaultHttpRequest與FullHttpRequest

本人用netty4.0做Http服務器模塊時,出現了一個Bug,從平臺發送過來的充值請求接收不到,充值請求是Post方式,自己寫了個post工具模擬充值請求,發現:能收到HttpRequest,但收不到HttpContent。

消息分發器代碼:

	protected void channelRead0(ChannelHandlerContext ctx, Object data)
			throws Exception {
if (data instanceof HttpRequest) {
.....
}
else if(data instanceof HttpContent){
....
}
}

這是以前沒出問題時的部分代碼,Post請求是分兩次收到的,一次是HttpRequest,只有Http 協議頭,一次是HttpContent,內容是data form數據。


消息處理鏈代碼:

		ChannelPipeline pipeline = channel.pipeline();
		pipeline.addLast(new HttpServerCodec());
		pipeline.addLast(HANDLER);

之後修改了消息處理鏈的代碼,因爲不能響應太長數據消息:

	@Override
	protected void initChannel(SocketChannel channel) throws Exception {
		ChannelPipeline pipeline = channel.pipeline();
		pipeline.addLast(new HttpServerCodec());
		pipeline.addLast( new HttpObjectAggregator(65536));
		pipeline.addLast(new ChunkedWriteHandler());
//		pipeline.addLast(new HttpRequestDecoder());
		pipeline.addLast(HANDLER);

添加HttpObjectAggregator和ChunkedWriteHandler,結果就出現了這個問題

相應的分發器代碼也要改

	protected void channelRead0(ChannelHandlerContext ctx, Object data)
			throws Exception {
		//DefaultHttpRequest
		//FullHttpRequest
		if(data instanceof FullHttpRequest){
			FullHttpRequest fhr = (FullHttpRequest)data;
			String uri = fhr.getUri();
			int platType = -1;
			int action = 0;
			if(uri.startsWith("/exchange")){
				platType = PlatformTypes.QIHOO;
				action = PlatformManager.ACTION_EXCHANGE;
				int len = fhr.content().readableBytes();
				if(len > 0){
					byte[] content = new byte[len];
					fhr.content().readBytes(content);
					String contentStr = new String(content, "UTF-8");
					Map<String, String> paramMap = HttpUtil.url2Map(contentStr);
					PlatformManager.getInstance().doAction(platType, action, paramMap, ctx.channel());
				}
				return;
			}
		}

FullHttpRequest的協議頭和Form數據是在一起的,不用分開讀,之前分開接收的是DefaultHttpRequest與HttpContent,FullHttpRequest把兩者合在一起了,Netty不熟悉就是容易出錯。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章