Netty4.0問題と解決-ChannelPipelineException

2881 ワード

最初は簡単なTCPサービスを書いて、テストもokでしたが、ツールでポートに接続したことに気づき、切断してから接続すると次のエラーが発生しました.
 
 
2013-03-26 13:54:05,283 WARN - Failed to initialize a channel. Closing: [id: 0x83d224f6, /127.0.0.1:2810 => /127.0.0.1:8080]
io.netty.channel.ChannelPipelineException: com.cocoon.test.netty.codec.MessageCodec is not a @Sharable handler, so can't be added or removed multiple times.
	at io.netty.channel.DefaultChannelPipeline.callBeforeAdd(DefaultChannelPipeline.java:628)
	at io.netty.channel.DefaultChannelPipeline.addLast0(DefaultChannelPipeline.java:200)
	at io.netty.channel.DefaultChannelPipeline.addLast(DefaultChannelPipeline.java:173)
	at io.netty.channel.DefaultChannelPipeline.addLast(DefaultChannelPipeline.java:161)
	at com.cocoon.test.netty.handler.PipelineFactory.initChannel(PipelineFactory.java:27)
	at com.cocoon.test.netty.handler.PipelineFactory.initChannel(PipelineFactory.java:1)
	at io.netty.channel.ChannelInitializer.channelRegistered(ChannelInitializer.java:70)
	at io.netty.channel.DefaultChannelHandlerContext.invokeChannelRegistered(DefaultChannelHandlerContext.java:673)
	at io.netty.channel.DefaultChannelHandlerContext.fireChannelRegistered(DefaultChannelHandlerContext.java:659)
	at io.netty.channel.DefaultChannelPipeline.fireChannelRegistered(DefaultChannelPipeline.java:957)
	at io.netty.channel.AbstractChannel$AbstractUnsafe.register0(AbstractChannel.java:608)
	at io.netty.channel.AbstractChannel$AbstractUnsafe.access$700(AbstractChannel.java:437)
	at io.netty.channel.AbstractChannel$AbstractUnsafe$5.run(AbstractChannel.java:585)
	at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:328)
	at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:331)
	at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:109)
	at java.lang.Thread.run(Thread.java:619)

 
 
その後、エラーを報告したhandlerの前に@sharableを付ける必要があることに気づきました.例えば、
 
@Sharable
public class TcpServerHandler extends ChannelInboundMessageHandlerAdapter<String> {

	private static final Logger logger = Logger.getLogger(TcpServerHandler.class.getName());

	@Override
	public void messageReceived(ChannelHandlerContext ctx, String request) throws Exception {
		logger.info("Receive:" + request);
		ChannelFuture future = ctx.write(request);
		future.addListener(ChannelFutureListener.CLOSE);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		logger.log(Level.WARNING, "Unexpected exception from downstream.", cause);
		ctx.close();
	}

}

 
 
これでいいです.