Search in sources :

Example 1 with FixedLengthFrameDecoder

use of io.netty.handler.codec.FixedLengthFrameDecoder in project java-in-action by xinghalo.

the class FixedEchoServer method bind.

private void bind() throws InterruptedException {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    try {
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new FixedLengthFrameDecoder(20));
                ch.pipeline().addLast(new StringDecoder());
                ch.pipeline().addLast(new EchoServerHandler());
            }
        });
        ChannelFuture f = b.bind(5555).sync();
        f.channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully().sync();
        workerGroup.shutdownGracefully().sync();
    }
}
Also used : NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) LoggingHandler(io.netty.handler.logging.LoggingHandler) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) FixedLengthFrameDecoder(io.netty.handler.codec.FixedLengthFrameDecoder) StringDecoder(io.netty.handler.codec.string.StringDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Example 2 with FixedLengthFrameDecoder

use of io.netty.handler.codec.FixedLengthFrameDecoder in project jdepth by Crab2died.

the class EchoServer method bind.

private void bind(int port) throws InterruptedException {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap bootstrap = new ServerBootstrap().group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new FixedLengthFrameDecoder(15)).addLast(new StringDecoder()).addLast(new EchoServerHandler());
            }
        });
        ChannelFuture future = bootstrap.bind(port).sync();
        future.channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
Also used : NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) LoggingHandler(io.netty.handler.logging.LoggingHandler) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) StringDecoder(io.netty.handler.codec.string.StringDecoder) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) FixedLengthFrameDecoder(io.netty.handler.codec.FixedLengthFrameDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 3 with FixedLengthFrameDecoder

use of io.netty.handler.codec.FixedLengthFrameDecoder in project jdepth by Crab2died.

the class EchoClient method connect.

private void connect(String host, int port) throws InterruptedException {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap bootstrap = new Bootstrap().group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, Boolean.TRUE).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(// 定长设置
                new FixedLengthFrameDecoder(15)).addLast(new StringDecoder()).addLast(new EchoClientHandler());
            }
        });
        ChannelFuture future = bootstrap.connect(host, port).sync();
        future.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) FixedLengthFrameDecoder(io.netty.handler.codec.FixedLengthFrameDecoder) StringDecoder(io.netty.handler.codec.string.StringDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 4 with FixedLengthFrameDecoder

use of io.netty.handler.codec.FixedLengthFrameDecoder in project netty by netty.

the class SocketFixedLengthEchoTest method testFixedLengthEcho.

private static void testFixedLengthEcho(ServerBootstrap sb, Bootstrap cb, boolean autoRead) throws Throwable {
    final EchoHandler sh = new EchoHandler(autoRead);
    final EchoHandler ch = new EchoHandler(autoRead);
    sb.childOption(ChannelOption.AUTO_READ, autoRead);
    sb.childHandler(new ChannelInitializer<Channel>() {

        @Override
        public void initChannel(Channel sch) throws Exception {
            sch.pipeline().addLast("decoder", new FixedLengthFrameDecoder(1024));
            sch.pipeline().addAfter("decoder", "handler", sh);
        }
    });
    cb.option(ChannelOption.AUTO_READ, autoRead);
    cb.handler(new ChannelInitializer<Channel>() {

        @Override
        public void initChannel(Channel sch) throws Exception {
            sch.pipeline().addLast("decoder", new FixedLengthFrameDecoder(1024));
            sch.pipeline().addAfter("decoder", "handler", ch);
        }
    });
    Channel sc = sb.bind().sync().channel();
    Channel cc = cb.connect(sc.localAddress()).sync().channel();
    for (int i = 0; i < data.length; ) {
        int length = Math.min(random.nextInt(1024 * 3), data.length - i);
        cc.writeAndFlush(Unpooled.wrappedBuffer(data, i, length));
        i += length;
    }
    while (ch.counter < data.length) {
        if (sh.exception.get() != null) {
            break;
        }
        if (ch.exception.get() != null) {
            break;
        }
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
        // Ignore.
        }
    }
    while (sh.counter < data.length) {
        if (sh.exception.get() != null) {
            break;
        }
        if (ch.exception.get() != null) {
            break;
        }
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
        // Ignore.
        }
    }
    sh.channel.close().sync();
    ch.channel.close().sync();
    sc.close().sync();
    if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
        throw sh.exception.get();
    }
    if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) {
        throw ch.exception.get();
    }
    if (sh.exception.get() != null) {
        throw sh.exception.get();
    }
    if (ch.exception.get() != null) {
        throw ch.exception.get();
    }
}
Also used : Channel(io.netty.channel.Channel) FixedLengthFrameDecoder(io.netty.handler.codec.FixedLengthFrameDecoder) IOException(java.io.IOException) IOException(java.io.IOException)

Example 5 with FixedLengthFrameDecoder

use of io.netty.handler.codec.FixedLengthFrameDecoder 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)

Aggregations

FixedLengthFrameDecoder (io.netty.handler.codec.FixedLengthFrameDecoder)5 StringDecoder (io.netty.handler.codec.string.StringDecoder)4 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)3 SocketChannel (io.netty.channel.socket.SocketChannel)3 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)2 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)2 LoggingHandler (io.netty.handler.logging.LoggingHandler)2 Bootstrap (io.netty.bootstrap.Bootstrap)1 ByteBuf (io.netty.buffer.ByteBuf)1 Unpooled (io.netty.buffer.Unpooled)1 Channel (io.netty.channel.Channel)1 ChannelHandler (io.netty.channel.ChannelHandler)1 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)1 DelimiterBasedFrameDecoder (io.netty.handler.codec.DelimiterBasedFrameDecoder)1 Delimiters (io.netty.handler.codec.Delimiters)1 StringEncoder (io.netty.handler.codec.string.StringEncoder)1 CharsetUtil (io.netty.util.CharsetUtil)1 IOException (java.io.IOException)1 Charset (java.nio.charset.Charset)1 ArrayList (java.util.ArrayList)1