netty 实例入门

简介: netty 实例入门   基于netty 4.x       package com.test.demo.java2015.netty; import java.net.ConnectException; import java.

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<String, Bootstrap> bootstrapMap = new ConcurrentHashMap<String, Bootstrap>();
    	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<Handler> channelList = new ArrayList<Handler>();
		
		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<SocketChannel>() {
				@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捐助),没钱捧个人场,谢谢各位。



 
 
 谢谢您的赞助,我会做的更好!

 

 

目录
相关文章
|
7天前
|
缓存 网络协议 算法
Netty的基础入门(上)
Netty的基础入门(上)
32 0
|
2月前
|
缓存 网络协议 算法
《跟闪电侠学Netty》阅读笔记 - Netty入门程序解析
《跟闪电侠学Netty》阅读笔记 - Netty入门程序解析
133 0
|
7月前
|
存储 网络协议 前端开发
Netty服务端和客户端开发实例—官方原版
Netty服务端和客户端开发实例—官方原版
106 0
|
2月前
|
消息中间件 缓存 Java
《跟闪电侠学Netty》阅读笔记 - 开篇入门Netty
《跟闪电侠学Netty》阅读笔记 - 开篇入门Netty
86 0
|
8月前
|
消息中间件 编解码 Java
Netty 入门指南
上文《[BIO、NIO、IO多路复用模型详细介绍&Java NIO 网络编程》](https://wangbinguang.blog.csdn.net/article/details/132047951)介绍了几种IO模型以及Java NIO,了解了在网络编程时使用哪种模型可以提高系统性能及效率。即使Java NIO可以帮助开发人员编写和维护网络应用程序,但由于其复杂性以及bug问题,还是诞生很多强大和流行的网络编程框架,比如Netty、Undertow、Grizzly,在平时的开发中大家更倾向于选择这些框架进行开发,而在我们学习和理解网络编程的底层原理时,使用Java NIO可以更加直接和深
42 0
|
4月前
|
缓存 网络协议 算法
《跟闪电侠学Netty》阅读笔记 - Netty入门程序解析(二)
《跟闪电侠学Netty》阅读笔记 - Netty入门程序解析
59 1
|
4月前
|
设计模式 网络协议 算法
《跟闪电侠学Netty》阅读笔记 - Netty入门程序解析(一)
《跟闪电侠学Netty》阅读笔记 - Netty入门程序解析(一)
81 1
《跟闪电侠学Netty》阅读笔记 - Netty入门程序解析(一)
|
4月前
|
消息中间件 缓存 Java
《跟闪电侠学Netty》阅读笔记 - 开篇入门Netty(二)
《跟闪电侠学Netty》阅读笔记 - 开篇入门Netty
81 1
《跟闪电侠学Netty》阅读笔记 - 开篇入门Netty(二)
|
4月前
|
缓存 Java 数据挖掘
《跟闪电侠学Netty》阅读笔记 - 开篇入门Netty(一)
《跟闪电侠学Netty》阅读笔记 - 开篇入门Netty
80 0
《跟闪电侠学Netty》阅读笔记 - 开篇入门Netty(一)
|
4月前
|
编解码 网络协议 Java
Netty基础入门学习
Netty基础入门学习
31 0