All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.fastchar.socket.server.core.FastSocketChooseHandler Maven / Gradle / Ivy

package com.fastchar.socket.server.core;

import com.fastchar.socket.server.tcp.FastTcpSocketServerChannelHandler;
import com.fastchar.socket.server.websocket.FastWebSocketServerChannelHandler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;

import java.util.List;

/**
 * @author 沈建(Janesen)
 * @date 2021/4/19 16:41
 */
 class FastSocketChooseHandler extends ByteToMessageDecoder {
    private static final String WEBSOCKET_PREFIX = "GET /";

    
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List list) throws Exception {
        String protocol = getBufStart(in);
        ChannelPipeline pipeline = ctx.pipeline();
        if (protocol.startsWith(WEBSOCKET_PREFIX) && protocol.contains("websocket")) {
            pipeline.addLast(new HttpServerCodec());
            pipeline.addLast(new ChunkedWriteHandler());
            pipeline.addLast(new HttpObjectAggregator(8192));
            pipeline.addLast(new FastWebSocketServerChannelHandler());
        } else {
            pipeline.addLast(new IdleStateHandler(60, 0, 0));
            pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
            pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
            pipeline.addLast(new FastTcpSocketServerChannelHandler());
        }
        in.resetReaderIndex();
        pipeline.remove(this.getClass());
    }

    private String getBufStart(ByteBuf in) {
        int length = in.readableBytes();
        in.markReaderIndex();
        byte[] content = new byte[length];
        in.readBytes(content);
        return new String(content);
    }


}