Netty4.0问题及解决——ChannelPipelineException

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

}

 

 

这样就行了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值