Netty自动分解协议

Netty自动分解协议
Netty 处理多个协议

public static class ProtocolHeadAdapter extends ChannelInboundHandlerAdapter {
		// 1 GET 请求指定的页面信息,并返回实体主体。
		// 2 HEAD 类似于get请求,只不过返回的响应中没有具体的内容,用于获取报头
		// 3 POST
		// 向指定资源提交数据进行处理请求(例如提交表单或者上传文件)。数据被包含在请求体中。POST请求可能会导致新的资源的建立和/或已有资源的修改。
		// 4 PUT 从客户端向服务器传送的数据取代指定的文档的内容。
		// 5 DELETE 请求服务器删除指定的页面。
		// 6 CONNECT HTTP/1.1协议中预留给能够将连接改为管道方式的代理服务器。
		// 7 OPTIONS 允许客户端查看服务器的性能。
		// 8 TRACE 回显服务器收到的请求,主要用于测试或诊断。
		final static String[] http_head = { "GET ", "HEAD ", "POST ", "PUT ", "DELETE ", "CONNECT ", "OPTIONS ",
				"TRACE " };
		final static byte[] mqtt_head = { 0x10, 0x00, 0x00, 0x00, 'M', 'Q', 'T', 'T' };

		void callDecode(ChannelHandlerContext ctx, ByteBuf in) {
			if (!in.isReadable())
				return;
			if (in.readableBytes() < 10) {
				return;
			}
			in.markReaderIndex();
			byte[] head = new byte[10];
			in.readBytes(head);
			in.resetReaderIndex();
			int i;
			int sum = 0;

			// mqtt
			for (i = 0; i < mqtt_head.length; i++) {
				if (mqtt_head[i] == head[i] || mqtt_head[i] == 0) {
					sum++;
				}
			}
			ChannelPipeline pipeline = ctx.pipeline();
			if (sum == mqtt_head.length) {
				pipeline.addLast("MqttDecoder", new MqttDecoder());
				pipeline.addLast("MqttEncoder", MqttEncoder.INSTANCE);
				pipeline.addLast("MqttServerHandler", new MqttServerHandler(mqttSessionManagent));
			} else {
				pipeline.addLast(new HttpServerCodec());
				pipeline.addLast(new HttpObjectAggregator(65536));
				pipeline.addLast(new ChunkedWriteHandler());
				pipeline.addLast(new HttpStaticFileServerHandler());
			}
			pipeline.remove(this);
		}

		@Override
		public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
			if (msg instanceof ByteBuf) {
				try {
					ByteBuf data = (ByteBuf) msg;
					callDecode(ctx, data);
				} catch (DecoderException e) {
					throw e;
				} catch (Throwable t) {
					throw new DecoderException(t);
				} finally {

				}
			} else {
				ctx.fireChannelRead(msg);
			}
			super.channelRead(ctx, msg);
		}

	}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值