use of io.netty.handler.codec.string.StringDecoder in project java by wavefrontHQ.
the class HistogramLineIngester method initChannel.
@Override
protected void initChannel(Channel ch) throws Exception {
// Round robin channel to handler assignment.
int idx = (int) (Math.abs(connectionId.getAndIncrement()) % handlers.size());
ChannelHandler handler = handlers.get(idx);
// Add decoders and timeout, add handler()
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new LineBasedFrameDecoder(MAXIMUM_FRAME_LENGTH, true, false), new StringDecoder(Charsets.UTF_8), new IdleStateHandler(CHANNEL_IDLE_TIMEOUT_IN_SECS_DEFAULT, 0, 0), new ChannelDuplexHandler() {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
if (((IdleStateEvent) evt).state() == IdleState.READER_IDLE) {
logger.warning("terminating connection to histogram client due to inactivity after " + CHANNEL_IDLE_TIMEOUT_IN_SECS_DEFAULT + "s: " + ctx.channel());
ctx.close();
}
}
}
}, handler);
}
use of 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);
}
}
use of 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());
}
use of 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();
}
}
use of 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]);
};
}
Aggregations