堆码时刻 2012-04-24
Hello World in Netty
1、HelloWorldServer
ServerBootstrapbootstrap=newServerBootstrap(new
NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
publicChannelPipelinegetPipeline(){
ChannelPipelinepipeline=Channels.pipeline();
pipeline.addLast("decoder",newStringDecoder());
pipeline.addLast("encoder",newStringEncoder());
pipeline.addLast("handler",newHelloWorldServerHandler());
returnpipeline;
}
});bootstrap.bind(new InetSocketAddress(8080));
HelloWorldServerHandler
publicvoidchannelConnected(ChannelHandlerContextctx,
ChannelStateEvente)throwsException{
e.getChannel().write("Hello,World");
}public void exceptionCaught(ChannelHandlerContext ctx,
ExceptionEvente){
logger.log(Level.WARNING,"Unexpectedexceptionfrom
downstream.",e.getCause());
e.getChannel().close();
}
2、HelloWorldClient
ClientBootstrapbootstrap=newClientBootstrap(newNioClientSocketChannelFactory(
Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
publicChannelPipelinegetPipeline(){
ChannelPipelinepipeline=pipeline();
pipeline.addLast("decoder",newStringDecoder());
pipeline.addLast("encoder",newStringEncoder());
pipeline.addLast("handler",newHelloWorldClientHandler());
returnpipeline;
}
});ChannelFuture future = bootstrap.connect(new InetSocketAddress("localhost", 8080));
future.getChannel().getCloseFuture().awaitUninterruptibly();
bootstrap.releaseExternalResources();
HelloWorldClientHandler
publicvoidmessageReceived(ChannelHandlerContextctx,
MessageEvente){
Stringmessage=(String)e.getMessage();
System.out.println(message);
e.getChannel().close();}
publicvoidexceptionCaught(ChannelHandlerContextctx,
ExceptionEvente){
logger.log(Level.WARNING,"Unexpectedexceptionfrom
downstream.",e.getCause());
e.getChannel().close();}