项目中netty的使用

public class NettyServer {
    
    private static final long serialVersionUID = 1L;
    private final static Logger LOG = LogManager.getLogger(NettyServer.class);
    public     final static Random RANDOM = new Random(System.currentTimeMillis());
    private static String[] calls = null;
    private static List<String> phones = null;// 存放所有重庆电话信息
    private final static String MESSAGE_SPLIT = "\r\r";
    private final static String ERROR_RESULT = "{}\n\n";
    private final static byte[] MESSAGE_END = "\n\n".getBytes();
    public     final static Message EMPTY_RECV_MESSAGE = new Message();
    private final static int MESSAGE_MIN_SIZE = "0.0.0.0:0#\n\n".getBytes().length;
    private final static Configuration conf = Configuration.getInstance();
    
    static {
        EMPTY_RECV_MESSAGE.type = 2;
    }
    
    
    public static void write(Channel ch,String text){
        byte[] bytes = text.getBytes();
        ChannelBuffer out = ChannelBuffers.buffer(bytes.length+MESSAGE_END.length);
        out.writeBytes(bytes);
        out.writeBytes(MESSAGE_END);
        if(ch.isOpen()){
            ChannelFuture f = ch.write(out);
            f.addListener(new ChannelFutureListener() {
                public void operationComplete(ChannelFuture future) {
                    Channel ch = future.getChannel();
                    ch.close();
                }
            });
        }
    }
    
    static class WebIMServerHandler extends IdleStateAwareChannelHandler {
        
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
            e.getCause().printStackTrace();

            Channel channel = e.getChannel();
            NettyConnection c = (NettyConnection)channel.getAttachment();
            if(c != null) c.setConnection(null);
            channel.close();
        }
        @Override
        public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) throws Exception {
            if(e.getState() == IdleState.ALL_IDLE) {
                Channel ch = e.getChannel();
                NettyConnection c = (NettyConnection)ch.getAttachment();
                if(c != null) {
                    c.setConnection(null);
                    String result = MessageCodec.encode(c, EMPTY_RECV_MESSAGE);
                    write(ch, result);
                }else{
                    write(ch, ERROR_RESULT);
                }
            }
            super.channelIdle(ctx, e);

        }

        @Override
        public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
            Channel ch = e.getChannel();
            ChannelBuffer in = (ChannelBuffer) e.getMessage();
            byte[] bytes = in.array();
            if(bytes.length < MESSAGE_MIN_SIZE) {
                ch.close();
                return;
            }
            String text = new String(bytes);    
        }
    }    
    
    static class WebIMPipelineFactory implements ChannelPipelineFactory {
        
        private final Timer timer;
        
        private final ChannelHandler idleStateHandler;

        public WebIMPipelineFactory(Timer timer) {
            this.timer = timer;
            this.idleStateHandler = new IdleStateHandler(timer, 20, 20, 20); // timer must be shared.
        }

        public ChannelPipeline getPipeline() {
            return Channels.pipeline(idleStateHandler, new WebIMServerHandler());
        }

        public Timer getTimer() {
            return timer;
        }
    }
    
    public static void start(String host, int port) throws Exception {
        ChannelFactory factory = new NioServerSocketChannelFactory(
                Executors.newCachedThreadPool(),
                Executors.newCachedThreadPool());

        ServerBootstrap bootstrap = new ServerBootstrap(factory);
        
        bootstrap.setPipelineFactory(new WebIMPipelineFactory(new HashedWheelTimer()));

        bootstrap.setOption("child.tcpNoDelay", true);
        bootstrap.setOption("child.keepAlive", false);
        bootstrap.setOption("reuseAddress", true);
        bootstrap.setOption("receiveBufferSize", 4096);
        bootstrap.setOption("allIdleTime", 20);
        bootstrap.bind(new InetSocketAddress(port));

        LOG.info(String.format("Socket-netty Server Start : %s:%d", host, port));
    }
}

你可能感兴趣的:(项目中netty的使用)