我计划将服务器部分中的配置文件读入内存并使用处理程序中的数据。
附上代码片段。
// 从示例目录
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);
}
}
但这不起作用。请任何人都可以将我指向正确的文档或给我一个提示,我可以如何实现这个计划。
感谢帮助。约翰