package com.shlanbao.tzsc.data.runtime.netty; import java.net.InetSocketAddress; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.handler.codec.frame.LengthFieldBasedFrameDecoder; import org.jboss.netty.handler.codec.frame.LengthFieldPrepender; import org.jboss.netty.handler.codec.string.StringDecoder; import org.jboss.netty.handler.codec.string.StringEncoder; import org.jboss.netty.handler.timeout.IdleStateHandler; import org.jboss.netty.util.HashedWheelTimer; /** * netty3.X 服务端 * * */ public class NettyServer implements ServletContextListener{ private Map mapChannel=new HashMap(); private static NettyServer instance=null; public static NettyServer getInstance() { if(instance==null) { instance=new NettyServer(); } return instance; } @Override public void contextInitialized(ServletContextEvent arg0) { String localAddress = arg0.getServletContext().getInitParameter("localAddress"); String localPort = arg0.getServletContext().getInitParameter("localPort"); //服务类 ServerBootstrap bootStrap=new ServerBootstrap(); //创建两个线程池 ExecutorService boss=Executors.newCachedThreadPool(); //线程池中的线程是client,主要负责端口的监听 ExecutorService worker=Executors.newCachedThreadPool(); //主要负责读写任务 //设置nio socket工厂 bootStrap.setFactory(new NioServerSocketChannelFactory(boss, worker)); final HashedWheelTimer hashedWheelTimer = new HashedWheelTimer(); //设置管道的工厂 bootStrap.setPipelineFactory(new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline=Channels.pipeline(); //解码 pipeline.addLast("decoder", new StringDecoder(Charset.forName("UTF-8"))); //编码 pipeline.addLast("encoder", new StringEncoder(Charset.forName("UTF-8"))); pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4)); pipeline.addLast("frameEncoder", new LengthFieldPrepender(4)); pipeline.addLast("idle",new IdleStateHandler(hashedWheelTimer,5,5,20)); pipeline.addLast("serverHandler", new ServerHandler()); return pipeline; } }); bootStrap.bind(new InetSocketAddress( localAddress,Integer.parseInt(localPort))); } @Override public void contextDestroyed(ServletContextEvent arg0) { // TODO Auto-generated method stub } public Map getMapChannel() { return mapChannel; } /** * 获得服务端Netty连接 * @author wan * */ public Channel getNettyChannel() { if(mapChannel.size()>0) { for( Entry m : mapChannel.entrySet()) { return m.getValue(); } } return null; } }