刚开始写了个简单的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();
}
}
这样就行了。