我计划将服务器部分中的配置文件读入内存并使用处理程序中的数据。
附上代码片段。
//来自示例目录
public class TelnetServer {
private final int port;
private final String myConfFile;
// MyConf is a singleton class which read the config
// from my app into memory
private static final AttributeKey<MyConf> myCAttribute = new AttributeKey<MyConf>("MyConf");
public TelnetServer(int port,String confFile) {
this.port = port;
this.myConfFile = confFile;
}
public void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.childAttr(myCAttribute, MyConf.getInstance(myConfFile));
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new TelnetServerInitializer());
b.bind(port).sync().channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
现在我想使用TelnetServerHandler中的值。
public void channelRead0(ChannelHandlerContext ctx, String request) throws Exception {
// Generate and write a response.
String response;
boolean close = false;
if (request.isEmpty()) {
response = "Please type something.\r\n";
} else if ("bye".equals(request.toLowerCase())) {
response = "Have a good day!\r\n";
close = true;
} else {
response = "Did you say '" + request + "'?\r\n";
MyConf mc = (MyConf)ctx.attr("MyConf");
}
// We do not need to write a ChannelBuffer here.
// We know the encoder inserted at TelnetPipelineFactory will do the conversion.
ChannelFuture future = ctx.write(response);
// Close the connection after sending 'Have a good day!'
// if the client has sent 'bye'.
if (close) {
future.addListener(ChannelFutureListener.CLOSE);
}
}
但这不起作用。 请任何人都可以指出正确的文件,或者给我一个提示,告诉我如何实现这个计划。
感谢您的帮助。 约翰
答案 0 :(得分:0)
我认为应该是
MyConf mc = ctx.attr(TelnetServer.myCAttribute).get();
我在我的项目中尝试过,并且在从频道上下文中获取属性时遇到了问题,并且必须从频道本身进入:
MyConf mc = ctx.channel().attr(TelnetServer.myCAttribute).get();
尝试其中一个适合你。