Netty+Protobuf+WebSocket/Socket后台服务端的对channel的处理

@Slf4j
@Component
public class NettyServerInitializer extends ChannelInitializer<SocketChannel> {


    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new PortUnificationServerHandler());
    }
}
package com.lsbc.game.server.handler;

import com.google.protobuf.MessageLite;
import com.google.protobuf.MessageLiteOrBuilder;
import com.lsbc.game.pojo.constant.ParatrooperConstant;
import com.lsbc.game.protobuf.RequestParamMsg;
import com.lsbc.hornet.auth.SpringContextUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 统一端口的处理器
 * <p>
 * 使用同一个端口去处理TCP/HTTP协议的请求,因为HTTP的底层协议也是TCP,因此可以在此处理器内部可以通过解析部分数据
 * 来判断请求是TCP请求还是HTTP请求,然使用动态的pipeline切换
 */
@Slf4j
public class PortUnificationServerHandler extends ByteToMessageDecoder {

    private NettyServerHandler nettyServerHandler= (NettyServerHandler)SpringContextUtils.getBean("nettyServerHandler");

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        // Will use the first five bytes to detect a protocol.
        if (byteBuf.readableBytes() < 5) {
            return;
        }
        final int magic1 = byteBuf.getUnsignedByte(byteBuf.readerIndex());
        final int magic2 = byteBuf.getUnsignedByte(byteBuf.readerIndex() + 1);

        // 判断是不是HTTP请求
        if (isHttp(magic1, magic2)) {
            log.info("this is a http msg");
            switchToHttp(channelHandlerContext);
        } else {
            log.info("this is a socket msg");
            switchToTcp(channelHandlerContext);
        }

    }

    /**
     * 跳转到http处理
     *
     * @param ctx
     */
    private void switchToHttp(ChannelHandlerContext ctx) {
        ChannelPipeline pipeline = ctx.pipeline();
        // HTTP请求的解码和编码
        pipeline.addLast(new HttpServerCodec());
        // 把多个消息转换为一个单一的FullHttpRequest或是FullHttpResponse,
        // 原因是HTTP解码器会在每个HTTP消息中生成多个消息对象HttpRequest/HttpResponse,HttpContent,LastHttpContent
        pipeline.addLast(new HttpObjectAggregator(65536));
        // 主要用于处理大数据流,比如一个1G大小的文件如果你直接传输肯定会撑暴jvm内存的; 增加之后就不用考虑这个问题了
        pipeline.addLast(new ChunkedWriteHandler());
        // WebSocket数据压缩
        pipeline.addLast(new WebSocketServerCompressionHandler());
        //设置路由;协议包长度限制 ;里面加入的WebSocketServerProtocolHandshakeHandler对路由下FullHttpRequest解码成WebSocketFrame
        pipeline.addLast(new WebSocketServerProtocolHandler("/", null, true));
        // 协议包解码
        //websocket消息帧处理看下面代码(这里需要把前台的消息分类,判断传过来的是websocket哪个帧,如果为二进制帧往下传值,让protobuf解码)
        pipeline.addLast(new MessageToMessageDecoder<WebSocketFrame>() {
            @Override
            protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Object> out) throws Exception {
                //文本帧处理(收到的消息广播到前台客户端)
                if (frame instanceof TextWebSocketFrame) {
                    log.info("文本帧消息:" + ((TextWebSocketFrame) frame).text());
                }
                //二进制帧处理,将帧的内容往下传
                else if (frame instanceof BinaryWebSocketFrame) {
                    BinaryWebSocketFrame binaryWebSocketFrame = (BinaryWebSocketFrame) frame;
                    byte[] by = new byte[frame.content().readableBytes()];
                    binaryWebSocketFrame.content().readBytes(by);
                    ByteBuf bytebuf = Unpooled.buffer();
                    bytebuf.writeBytes(by);
                    out.add(bytebuf);
                } else if (frame instanceof PingWebSocketFrame) {
                    log.info("其它帧消息" + frame.toString());
                }
            }
        });
        // 协议包编码
        pipeline.addLast(new MessageToMessageEncoder<MessageLiteOrBuilder>() {
            @Override
            protected void encode(ChannelHandlerContext ctx, MessageLiteOrBuilder msg, List<Object> out) throws Exception {
                ByteBuf result = null;
                if (msg instanceof MessageLite) {
                    result = Unpooled.wrappedBuffer(((MessageLite) msg).toByteArray());
                }
                if (msg instanceof MessageLite.Builder) {
                    result = Unpooled.wrappedBuffer(((MessageLite.Builder) msg).build().toByteArray());
                }
                // ==== 上面代码片段是拷贝自TCP ProtobufEncoder 源码 ====
                // 然后下面再转成websocket二进制流,因为客户端不能直接解析protobuf编码生成的
                WebSocketFrame frame = new BinaryWebSocketFrame(result);
                out.add(frame);
            }
        });
        //入参说明: 读超时时间、写超时时间、所有类型的超时时间、时间格式
        pipeline.addLast(new IdleStateHandler(ParatrooperConstant.NettyConstant.SERVER_READER_IDLE_TIME, ParatrooperConstant.NettyConstant.SERVER_WRITER_IDLE_TIME, ParatrooperConstant.NettyConstant.SERVER_ALL_IDLE_TIME, TimeUnit.SECONDS));
        // 解码和编码,应和客户端一致
        // 传输的协议 Protobuf
        /**
         * 前端用websocket通信,此处的ProtobufVarint32FrameDecoder和ProtobufVarint32LengthFieldPrepender对分包、粘包的处理反而影响数据的转换
         * 估计原因应是前面把多个消息转换为一个单一的FullHttpRequest或是FullHttpResponse导致
         * 如果不用websocket加上分包、粘包的处理就可以
         */
//        pipeline.addLast(new ProtobufVarint32FrameDecoder());
        pipeline.addLast(new ProtobufDecoder(RequestParamMsg.RequestParam.getDefaultInstance()));
//        pipeline.addLast(new ProtobufVarint32LengthFieldPrepender());
        pipeline.addLast(nettyServerHandler);
        pipeline.remove(this);
    }


    /**
     * 判断请求是否是HTTP请求
     *
     * @param magic1 报文第一个字节
     * @param magic2 报文第二个字节
     * @return
     */
    private boolean isHttp(int magic1, int magic2) {
        return magic1 == 'G' && magic2 == 'E' || // GET
                magic1 == 'P' && magic2 == 'O' || // POST
                magic1 == 'P' && magic2 == 'U' || // PUT
                magic1 == 'H' && magic2 == 'E' || // HEAD
                magic1 == 'O' && magic2 == 'P' || // OPTIONS
                magic1 == 'P' && magic2 == 'A' || // PATCH
                magic1 == 'D' && magic2 == 'E' || // DELETE
                magic1 == 'T' && magic2 == 'R' || // TRACE
                magic1 == 'C' && magic2 == 'O';   // CONNECT
    }

    /**
     * 跳转到http处理
     *
     * @param ctx
     */
    private void switchToTcp(ChannelHandlerContext ctx) {
        ChannelPipeline pipeline = ctx.pipeline();
        //入参说明: 读超时时间、写超时时间、所有类型的超时时间、时间格式
        pipeline.addLast(new IdleStateHandler(ParatrooperConstant.NettyConstant.SERVER_READER_IDLE_TIME, ParatrooperConstant.NettyConstant.SERVER_WRITER_IDLE_TIME, ParatrooperConstant.NettyConstant.SERVER_ALL_IDLE_TIME, TimeUnit.SECONDS));
        // 解码和编码,应和客户端一致
        // 传输的协议 Protobuf
        /**
         * 前端用websocket通信,此处的ProtobufVarint32FrameDecoder和ProtobufVarint32LengthFieldPrepender对分包、粘包的处理反而影响数据的转换
         * 估计原因应是前面把多个消息转换为一个单一的FullHttpRequest或是FullHttpResponse导致
         * 如果不用websocket加上分包、粘包的处理就可以
         */
        pipeline.addLast(new ProtobufVarint32FrameDecoder());
        pipeline.addLast(new ProtobufDecoder(RequestParamMsg.RequestParam.getDefaultInstance()));
        pipeline.addLast(new ProtobufVarint32LengthFieldPrepender());
        pipeline.addLast(new ProtobufEncoder());
        pipeline.addLast(nettyServerHandler);
        pipeline.remove(this);
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值