netty 实例入门

阅读更多

netty 实例入门

  基于netty 4.x

 

 

 

package com.test.demo.java2015.netty;

import java.net.ConnectException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean; 
import javax.net.ssl.SSLHandshakeException; 
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.ssl.SslHandshakeCompletionEvent;

public class NettyTest {

	public static void main(String[] args) { 
	}
	
    class  BootstrapFactory{
    	private ConcurrentHashMap bootstrapMap = new ConcurrentHashMap();
    	private  EventLoopGroup eventLoopGroup = new NioEventLoopGroup(1, null);
    	
    	public Bootstrap create(final String appname){
    		Bootstrap bootstrap = bootstrapMap.get(appname);
    		if (bootstrap == null)
    		{
    			bootstrap = new Bootstrap();
    			bootstrap.group(eventLoopGroup);
    			bootstrap.channel(NioSocketChannel.class);
    			bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    			bootstrap = bootstrapMap.putIfAbsent(appname, bootstrap);
    		}
    		return bootstrapMap.get(appname);
    	}
    } 
	 
	class NettyPool {
		private String host;
		private int port;
		private Bootstrap bootstrap;
		private int maxNum; 
		private int nextChannel = 0;
		List channelList = new ArrayList();
		
		public boolean write(String data)
		{
			return getAvailableHandler().write(data);
		}
		
		private synchronized Handler getAvailableHandler()
		{
			Handler handler;
			int count = this.maxNum;
			while ((handler = getHandler()) == null || handler.getChannel() == null
					|| !handler.getChannel().isWritable())
			{
				if (count-- == 0)
					break;
			}
			return handler;
		}
		
		private synchronized  Handler getHandler(){
			if (nextChannel >= maxNum)
			{
				nextChannel = 0;
			}
			Handler handler = channelList.get(nextChannel++);
			return handler;
		}
		
		
		
		NettyPool(int num, Bootstrap bootstrap, String host, int port) {
			this.maxNum = num;
			this.bootstrap = bootstrap;
			this.host = host;
			this.port = port;
		}

		public Bootstrap newBootstrap(Bootstrap bootstrap, final Handler handler) {
			bootstrap.handler(new ChannelInitializer() {
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					ChannelPipeline pipeline = ch.pipeline();
					/*
					 * if (isSsl) { SSLEngine sslEngine =
					 * sslContext.createSSLEngine();
					 * sslEngine.setUseClientMode(true); pipeline.addLast("ssl",
					 * new SslHandler(sslEngine)); } if (Constant.debug) {
					 * pipeline.addLast("log", new
					 * LoggingHandler(LogLevel.DEBUG)); }
					 * pipeline.addLast("encoder", new Encoder());
					 * pipeline.addLast("decoder", new Decoder());
					 */
					pipeline.addLast("handler", handler);
				}
			});
			return bootstrap;
		}

		public void start() {
			for (int i = 0; i < maxNum; i++) {
				Handler handler = new Handler(this);
				ChannelFuture future = newBootstrap(bootstrap, handler)
						.connect(host, port);
				if (future.isSuccess()) {

				} else 
				{
				}
			}
		}

		public void reconnect(Handler reHandler)
		{
			new ReConnectThread(reHandler).start();
		}
		
		public class ReConnectThread extends Thread{
			private Handler reHandler;
			public ReConnectThread(Handler handler) {
				this.reHandler = handler;
			}

			@Override
			public void run() {
				ChannelFuture future = newBootstrap(bootstrap, reHandler)
				.connect(host, port);
				if (future.isSuccess()) {
		
				} else 
				{
				}
			}
		}
		
		
		
	}
	
	
	/**
	 * 
	 * channelopen channelbound channelconnected -> channelactive channeldisconnected channelunbound channelclosed ->channelinactive
	 * channel.isbound() channel.isconnected() -> isactive() registered ->channelopen unregistered -> channelclosed
	 * 
	 */
	@Sharable
	class Handler extends SimpleChannelInboundHandler {
		private Channel channel;
		public NettyPool pool;
		private AtomicBoolean isShouldShutDown = new AtomicBoolean(false);
		
		
		public boolean write(String data){
			synchronized (this)
			{
				if (channel != null && channel.isWritable())
				{
					channel.writeAndFlush(data).addListener(new ChannelFutureListener(){
						@Override
						public void operationComplete(ChannelFuture future)
								throws Exception {
							if (future.isSuccess())
							{
								//log write success 
							}else{
								//log write  error
							}
						}
					});
					return false;
				}else
				{
					return false;
				}
			}
		}
		
		public Channel getChannel()
		{
			return this.channel;
		}
		
		public Handler(NettyPool pool) {
			this.pool = pool;
		}

		@Override
		protected void channelRead0(ChannelHandlerContext ctx, Object msg)
				throws Exception {

		}

		@Override
		public void channelActive(ChannelHandlerContext ctx) throws Exception {
			super.channelActive(ctx);
			this.channel = ctx.channel();
		}

		@Override
		public void channelRegistered(ChannelHandlerContext ctx)
				throws Exception {
			super.channelRegistered(ctx);
		}

		@Override
		public void channelUnregistered(ChannelHandlerContext ctx)
				throws Exception {
			ctx.close();
			if (!isShouldShutDown.get())
				this.pool.reconnect(this);
		}

		@Override
		public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
				throws Exception {
			if (cause instanceof ConnectException)
			{
				ctx.close();
				if (!isShouldShutDown.get())
					this.pool.reconnect(this);
			}
		}

		@Override
		public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
				throws Exception {
			if (evt instanceof SslHandshakeCompletionEvent)
			{
				if (((SslHandshakeCompletionEvent) evt).isSuccess())
				{}else{}
			}else if (evt instanceof SSLHandshakeException)
			{ }
		}
	}
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

捐助开发者

在兴趣的驱动下,写一个免费的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(右上角的爱心标志,支持支付宝和PayPal捐助),没钱捧个人场,谢谢各位。


netty 实例入门_第1张图片netty 实例入门_第2张图片netty 实例入门_第3张图片
 
 
 谢谢您的赞助,我会做的更好!

 

 

你可能感兴趣的:(netty,netty4.x,实例,入门)