标签:style java os strong io for cti ar
A ChannelHandler often needs to store some stateful information. The simplest and recommended approach is to use member variables:
public interface Message { // your methods here } public class DataServerHandler extends SimpleChannelInboundHandler<Message> { private boolean loggedIn; @Override public void channelRead0(ChannelHandlerContext ctx, Message message) { Channel ch = e.getChannel(); if (message instanceof LoginMessage) { authenticate((LoginMessage) message); loggedIn = true; } else (message instanceof GetDataMessage) { if (loggedIn) { ch.write(fetchSecret((GetDataMessage) message)); } else { fail(); } } } ... }
Because the handler instance has a state variable(状态变量) which is dedicated(专用) to one connection, you have to create a new handler instance for each new channel to avoid a race condition(竞态条件) where a unauthenticated(未验证的) client can get the confidential(机密的) information:
// Create a new handler instance per channel. // See ChannelInitializer.initChannel(Channel). public class DataServerInitializer extends ChannelInitializer<Channel> { @Override public void initChannel(Channel channel) { channel.pipeline().addLast("handler", new DataServerHandler()); } }
当出现这样的错误提示时,有两种解决方法,要么就是加上注解@Sharable,要么就是每次都new一个新的handler的实例。
====END====
netty4——is not a @Sharable handler,布布扣,bubuko.com
netty4——is not a @Sharable handler
标签:style java os strong io for cti ar
原文地址:http://my.oschina.net/xinxingegeya/blog/295577