java netty简单使用

NioServerSocketChannelFactory创建服务端的ServerSocketChannel,采用多线程执行非阻塞IO,和Mina的设计

模式一样,都采用了Reactor模式。其中bossExecutor、workerExecutor是两个线程池,bossExecutor用来接收客户端连接,

workerExecutor用来执行非阻塞的IO操作,主要是read,write。 

使用到的jar 

 <dependency>
            <groupId>org.jboss.netty</groupId>
            <artifactId>netty</artifactId>
            <version>3.2.9.Final</version>
        </dependency>
  </dependencies>



import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;

public class DiscardServer {
	public static void main(String[] args) {
		// Server服务启动器
		ServerBootstrap bootstrap = new ServerBootstrap(
				new NioServerSocketChannelFactory(
						Executors.newCachedThreadPool(),
						Executors.newCachedThreadPool()));
		// 设置一个处理客户端消息和各种消息事件的类(Handler)
		bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
			@Override
			public ChannelPipeline getPipeline() throws Exception {
				ChannelPipeline pipeline = Channels.pipeline();  
				pipeline.addLast("encode",new StringEncoder());  
                pipeline.addLast("decode",new StringDecoder());
                pipeline.addLast("handler",new HelloServerHandler());  
				return pipeline;
			}
		});
		// 开放8000端口供客户端访问。
		bootstrap.bind(new InetSocketAddress(8000));
	}

	private static class HelloServerHandler extends SimpleChannelHandler {
		/**
		 * 当有客户端绑定到服务端的时候触发,打印"Hello world, I'm server."
		 * 
		 * @alia OneCoder
		 * @author lihzh
		 */
		@Override
		public void channelConnected(ChannelHandlerContext ctx,
				ChannelStateEvent e) {
			System.out.println("Hello world, I'm server.");
		}	

		@Override
		public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
				throws Exception {
			String message = (String) e.getMessage();
			System.out.println(message);
			e.getChannel().close();
		}

		@Override
		public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
				throws Exception {
			System.out.println("服务端异常"+e.getCause());
			e.getChannel().close();
		}
	}

}

public class HelloClient {
	 // Client服务启动器  
    private static ClientBootstrap bootstrap = new ClientBootstrap(  
            new NioClientSocketChannelFactory(  
                    Executors.newCachedThreadPool(),  
                    Executors.newCachedThreadPool()));
    public static int i=0;
	public static void main(String args[]) throws InterruptedException {  
		while(true) {
        // 设置一个处理服务端消息和各种消息事件的类(Handler)  
		bootstrap.setPipelineFactory(new ChannelPipelineFactory() {  
            @Override  
            public ChannelPipeline getPipeline() throws Exception {
            	 ChannelPipeline pipeline = Channels.pipeline(); 
            	 pipeline.addLast("encode",new StringEncoder());  
                 pipeline.addLast("decode",new StringDecoder());  
                 pipeline.addLast("handler",new HelloClientHandler());  
                return pipeline;  
            }  
        });  
		
        // 连接到本地的8000端口的服务端  
        bootstrap.connect(new InetSocketAddress(  
                "127.0.0.1", 8000));
        System.out.println("计数:"+(i++));
		}
    }  
  
    private static class HelloClientHandler extends SimpleChannelHandler {  
  
  
        @Override
		public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
				throws Exception {
        	System.out.println("客服端---"+e.getCause());
		}

		/** 
         * 当绑定到服务端的时候触发,打印"Hello world, I'm client." 
         *  
         * @alia OneCoder 
         * @author lihzh 
         */  
        @Override  
        public void channelConnected(ChannelHandlerContext ctx,  
                ChannelStateEvent e) {  
            e.getChannel().write("xxxxxxxxxxxxx");
        }

		@Override
		public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
				throws Exception {
			 e.getChannel().close();
		}

    }  

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值