异步的、事件驱动的网络应用程序框架跟工具Netty
Hello World in Netty
1、HelloWorldServer
ServerBootstrap bootstrap = new ServerBootstrap(new
NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("handler", new HelloWorldServerHandler());
return pipeline;
}
});
bootstrap.bind(new InetSocketAddress(8080));
HelloWorldServerHandler
public void channelConnected(ChannelHandlerContext ctx,
ChannelStateEvent e) throws Exception {
e.getChannel().write("Hello, World");
}
public void exceptionCaught(ChannelHandlerContext ctx,
ExceptionEvent e) {
logger.log(Level.WARNING, "Unexpected exception from
downstream.", e.getCause());
e.getChannel().close();
}
2、HelloWorldClient
ClientBootstrap bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() {
ChannelPipeline pipeline = pipeline();
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("handler", new HelloWorldClientHandler());
return pipeline;
}
});
ChannelFuture future = bootstrap.connect(new InetSocketAddress("localhost", 8080));
future.getChannel().getCloseFuture().awaitUninterruptibly();
bootstrap.releaseExternalResources();
HelloWorldClientHandler
public void messageReceived(ChannelHandlerContext ctx,
MessageEvent e) {
String message = (String) e.getMessage();
System.out.println(message);
e.getChannel().close();
}
public void exceptionCaught(ChannelHandlerContext ctx,
ExceptionEvent e) {
logger.log(Level.WARNING, "Unexpected exception from
downstream.", e.getCause());
e.getChannel().close();
}