I'm using LengthFieldBasedFrameDecoder to send and receive byte[] but client gets error java.nio.channels.ClosedChannelException after it writes.
Here is pipeline factory;
@Override
public ChannelPipeline getPipeline() throws Exception {
String charSet = EvamProperties.charSet.get();
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("framer", new LengthFieldBasedFrameDecoder(1000000,0,4,0,4));//16KB
pipeline.addLast("decoder", new OneToOneDecoder() {
@Override
protected Object decode(ChannelHandlerContext channelHandlerContext, Channel channel, Object o) throws Exception {
if (!(o instanceof ChannelBuffer)) {
return o;
}
ChannelBuffer buffer = (ChannelBuffer) o;
int length = buffer.readInt();
byte[] bytes = new byte[length];
buffer.readBytes(bytes);
return bytes;
}
});
pipeline.addLast("encoder", new OneToOneEncoder() {
@Override
protected Object encode(ChannelHandlerContext channelHandlerContext, Channel channel, Object o) throws Exception {
if(!(o instanceof byte[])) {
return o;
}
ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeInt(((byte[]) o).length);
buffer.writeBytes((byte[])o);
return buffer;
}
});
pipeline.addLast("handler", new RawEventServerHandler());
return pipeline;
}
Client write it in this way;
channel.write(eventStr.getBytes());
In this code for debugging purposes data to send is String but I can't use StringDecoder.
Does LenghtFieldBasedDecoder is correct method to send and receive byte[] , if not, how can I do it?
edit:
I found that another thread actually closing the channel so java.nio.channels.ClosedChannelException is solved but I'm still eager to learn best practices for this kind of job.
writeAndFlush). Second, theClosedChannelExceptionmeans you try to read or write from / to the channel while it is already closed. There may be several reasons. What is yourRawEventServerHandleron both sides client and server ?