Search in sources :

Example 46 with StringDecoder

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.string.StringDecoder in project dubbo by alibaba.

the class QosProcessHandler method decode.

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (in.readableBytes() < 1) {
        return;
    }
    // read one byte to guess protocol
    final int magic = in.getByte(in.readerIndex());
    ChannelPipeline p = ctx.pipeline();
    p.addLast(new LocalHostPermitHandler(acceptForeignIp));
    if (isHttp(magic)) {
        // no welcome output for http protocol
        if (welcomeFuture != null && welcomeFuture.isCancellable()) {
            welcomeFuture.cancel(false);
        }
        p.addLast(new HttpServerCodec());
        p.addLast(new HttpObjectAggregator(1048576));
        p.addLast(new HttpProcessHandler());
        p.remove(this);
    } else {
        p.addLast(new LineBasedFrameDecoder(2048));
        p.addLast(new StringDecoder(CharsetUtil.UTF_8));
        p.addLast(new StringEncoder(CharsetUtil.UTF_8));
        p.addLast(new IdleStateHandler(0, 0, 5 * 60));
        p.addLast(new TelnetIdleEventHandler());
        p.addLast(new TelnetProcessHandler());
        p.remove(this);
    }
}
Also used : StringEncoder(io.netty.handler.codec.string.StringEncoder) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) LineBasedFrameDecoder(io.netty.handler.codec.LineBasedFrameDecoder) StringDecoder(io.netty.handler.codec.string.StringDecoder) ChannelPipeline(io.netty.channel.ChannelPipeline)

Example 47 with StringDecoder

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.string.StringDecoder in project chuidiang-ejemplos by chuidiang.

the class ServerWithNettyHandlers method run.

public void run() throws Exception {
    // (1)
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        // (2)
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(// (3)
        NioServerSocketChannel.class).childHandler(new // (4)
        ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new LineBasedFrameDecoder(1000));
                ch.pipeline().addLast(new LineEncoder(Charset.defaultCharset()));
                ch.pipeline().addLast(new StringDecoder(Charset.defaultCharset()));
                ch.pipeline().addLast(serverHandler);
            }
        }).option(ChannelOption.SO_BACKLOG, // (5)
        128).childOption(ChannelOption.SO_KEEPALIVE, // (6)
        true);
        // Bind and start to accept incoming connections.
        // (7)
        ChannelFuture f = b.bind(port).sync();
        // Wait until the server socket is closed.
        // In this example, this does not happen, but you can do that to gracefully
        // shut down your server.
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) LineEncoder(io.netty.handler.codec.string.LineEncoder) LineBasedFrameDecoder(io.netty.handler.codec.LineBasedFrameDecoder) StringDecoder(io.netty.handler.codec.string.StringDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Example 48 with StringDecoder

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.string.StringDecoder in project openremote by openremote.

the class AbstractIOClientProtocol method getGenericStringEncodersAndDecoders.

/**
 * Supplies a set of encoders/decoders that convert from/to {@link String} to/from {@link ByteBuf} based on the generic protocol {@link Attribute}s
 */
public static Supplier<ChannelHandler[]> getGenericStringEncodersAndDecoders(AbstractNettyIOClient<String, ?> client, IOAgent<?, ?, ?> agent) {
    boolean hexMode = agent.getMessageConvertHex().orElse(false);
    boolean binaryMode = agent.getMessageConvertBinary().orElse(false);
    Charset charset = agent.getMessageCharset().map(Charset::forName).orElse(CharsetUtil.UTF_8);
    int maxLength = agent.getMessageMaxLength().orElse(Integer.MAX_VALUE);
    String[] delimiters = agent.getMessageDelimiters().orElse(new String[0]);
    boolean stripDelimiter = agent.getMessageStripDelimiter().orElse(false);
    return () -> {
        List<ChannelHandler> encodersDecoders = new ArrayList<>();
        if (hexMode || binaryMode) {
            encodersDecoders.add(new AbstractNettyIOClient.MessageToByteEncoder<>(String.class, client, (msg, out) -> {
                byte[] bytes = hexMode ? ProtocolUtil.bytesFromHexString(msg) : ProtocolUtil.bytesFromBinaryString(msg);
                out.writeBytes(bytes);
            }));
            if (delimiters.length > 0) {
                ByteBuf[] byteDelimiters = Arrays.stream(delimiters).map(delim -> Unpooled.wrappedBuffer(hexMode ? ProtocolUtil.bytesFromHexString(delim) : ProtocolUtil.bytesFromBinaryString(delim))).toArray(ByteBuf[]::new);
                encodersDecoders.add(new DelimiterBasedFrameDecoder(maxLength, stripDelimiter, byteDelimiters));
            } else {
                encodersDecoders.add(new FixedLengthFrameDecoder(maxLength));
            }
            // Incoming messages will be bytes
            encodersDecoders.add(new AbstractNettyIOClient.ByteToMessageDecoder<>(client, (byteBuf, messages) -> {
                byte[] bytes = new byte[byteBuf.readableBytes()];
                byteBuf.readBytes(bytes);
                String msg = hexMode ? ProtocolUtil.bytesToHexString(bytes) : ProtocolUtil.bytesToBinaryString(bytes);
                messages.add(msg);
            }));
        } else {
            encodersDecoders.add(new StringEncoder(charset));
            if (agent.getMessageMaxLength().isPresent()) {
                encodersDecoders.add(new FixedLengthFrameDecoder(maxLength));
            } else {
                ByteBuf[] byteDelimiters;
                if (delimiters.length > 0) {
                    byteDelimiters = Arrays.stream(delimiters).map(delim -> Unpooled.wrappedBuffer(delim.getBytes(charset))).toArray(ByteBuf[]::new);
                } else {
                    byteDelimiters = Delimiters.lineDelimiter();
                }
                encodersDecoders.add(new DelimiterBasedFrameDecoder(maxLength, stripDelimiter, byteDelimiters));
            }
            encodersDecoders.add(new StringDecoder(charset));
            encodersDecoders.add(new AbstractNettyIOClient.MessageToMessageDecoder<>(String.class, client));
        }
        return encodersDecoders.toArray(new ChannelHandler[0]);
    };
}
Also used : Arrays(java.util.Arrays) Protocol(org.openremote.model.asset.agent.Protocol) ConnectionStatus(org.openremote.model.asset.agent.ConnectionStatus) Supplier(java.util.function.Supplier) Unpooled(io.netty.buffer.Unpooled) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) AgentLink(org.openremote.model.asset.agent.AgentLink) ByteBuf(io.netty.buffer.ByteBuf) Charset(java.nio.charset.Charset) Attribute(org.openremote.model.attribute.Attribute) AttributeEvent(org.openremote.model.attribute.AttributeEvent) CharsetUtil(io.netty.util.CharsetUtil) SyslogCategory(org.openremote.model.syslog.SyslogCategory) StringEncoder(io.netty.handler.codec.string.StringEncoder) Logger(java.util.logging.Logger) DelimiterBasedFrameDecoder(io.netty.handler.codec.DelimiterBasedFrameDecoder) FixedLengthFrameDecoder(io.netty.handler.codec.FixedLengthFrameDecoder) AbstractProtocol(org.openremote.agent.protocol.AbstractProtocol) Container(org.openremote.model.Container) PROTOCOL(org.openremote.model.syslog.SyslogCategory.PROTOCOL) List(java.util.List) StringDecoder(io.netty.handler.codec.string.StringDecoder) ChannelHandler(io.netty.channel.ChannelHandler) Agent(org.openremote.model.asset.agent.Agent) ProtocolUtil(org.openremote.model.protocol.ProtocolUtil) Delimiters(io.netty.handler.codec.Delimiters) DelimiterBasedFrameDecoder(io.netty.handler.codec.DelimiterBasedFrameDecoder) Charset(java.nio.charset.Charset) StringDecoder(io.netty.handler.codec.string.StringDecoder) ChannelHandler(io.netty.channel.ChannelHandler) ByteBuf(io.netty.buffer.ByteBuf) StringEncoder(io.netty.handler.codec.string.StringEncoder) FixedLengthFrameDecoder(io.netty.handler.codec.FixedLengthFrameDecoder) ArrayList(java.util.ArrayList) List(java.util.List)

Example 49 with StringDecoder

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.string.StringDecoder in project tech by ffyyhh995511.

the class HelloServerInitializer method initChannel.

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    // 以("\n")为结尾分割的 解码器
    pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    // 字符串解码 和 编码
    pipeline.addLast("decoder", new StringDecoder());
    pipeline.addLast("encoder", new StringEncoder());
    // 自己的逻辑Handler
    pipeline.addLast("handler", new HelloServerHandler());
}
Also used : StringEncoder(io.netty.handler.codec.string.StringEncoder) DelimiterBasedFrameDecoder(io.netty.handler.codec.DelimiterBasedFrameDecoder) StringDecoder(io.netty.handler.codec.string.StringDecoder) ChannelPipeline(io.netty.channel.ChannelPipeline)

Example 50 with StringDecoder

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.string.StringDecoder in project pancm_project by xuwujing.

the class NettyServerDemo2 method start.

/**
 * Start.
 */
public void start() {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap sbs = new ServerBootstrap().group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).localAddress(new InetSocketAddress(port)).childHandler(new ChannelInitializer<SocketChannel>() {

            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                // 字节解码器 ,其中2048是规定一行数据最大的字节数。  用于解决拆包问题
                p.addLast(new LineBasedFrameDecoder(2048));
                // p.addLast(new FixedLengthFrameDecoder(100));   //定长数据帧的解码器 ,每帧数据100个字节就切分一次。  用于解决粘包问题
                // p.addLast(new DelimiterBasedFrameDecoder(1024,Unpooled.copiedBuffer("~_~".getBytes()))); //固定字符切分解码器 ,会以"~_~"为分隔符。  注意此方法要放到StringDecoder()上面
                // 设置解码器
                p.addLast(new StringDecoder());
                // 绑定自定义事物
                p.addLast(new NettyServerHandlerDemo2());
            }
        }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
        // 绑定端口,开始接收进来的连接
        ChannelFuture future = sbs.bind(port).sync();
        System.out.println("服务端启动成功,端口为 :" + port);
        future.channel().closeFuture().sync();
    } catch (Exception e) {
        // 关闭EventLoopGroup,释放掉所有资源包括创建的线程
        bossGroup.shutdownGracefully();
        // 关闭EventLoopGroup,释放掉所有资源包括创建的线程
        workerGroup.shutdownGracefully();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) InetSocketAddress(java.net.InetSocketAddress) LineBasedFrameDecoder(io.netty.handler.codec.LineBasedFrameDecoder) StringDecoder(io.netty.handler.codec.string.StringDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline)

Aggregations

StringDecoder (io.netty.handler.codec.string.StringDecoder)63 StringEncoder (io.netty.handler.codec.string.StringEncoder)42 ChannelPipeline (io.netty.channel.ChannelPipeline)35 SocketChannel (io.netty.channel.socket.SocketChannel)27 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)21 ChannelFuture (io.netty.channel.ChannelFuture)18 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)16 DelimiterBasedFrameDecoder (io.netty.handler.codec.DelimiterBasedFrameDecoder)16 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)15 Bootstrap (io.netty.bootstrap.Bootstrap)14 EventLoopGroup (io.netty.channel.EventLoopGroup)14 LineBasedFrameDecoder (io.netty.handler.codec.LineBasedFrameDecoder)14 LengthFieldPrepender (io.netty.handler.codec.LengthFieldPrepender)13 LengthFieldBasedFrameDecoder (io.netty.handler.codec.LengthFieldBasedFrameDecoder)12 Channel (io.netty.channel.Channel)11 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)11 LoggingHandler (io.netty.handler.logging.LoggingHandler)8 ChannelHandler (io.netty.channel.ChannelHandler)6 IdleStateHandler (io.netty.handler.timeout.IdleStateHandler)6 Test (org.junit.Test)6