首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

异步的、事件驱动的网络应用程序框架跟工具Netty

2012-06-30 
异步的、事件驱动的网络应用程序框架和工具NettyHello World in Netty ??? 1、HelloWorldServer ???? Server

异步的、事件驱动的网络应用程序框架和工具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();

???? }

热点排行