All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.zlyx.easynetty.server.core.AbstractNettyServer Maven / Gradle / Ivy

package com.zlyx.easynetty.server.core;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;
 
import com.zlyx.easycore.tool.EasyBuffer;
 
/**
 * 
 * @Auth 赵光
 * @Describle 抽象netty服务端
 * @2019年1月25日 下午2:45:23
 */
@Sharable
public abstract class AbstractNettyServer extends ChannelInboundHandlerAdapter{

	/**
	 * 读数据
	 */
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            byte[] bytes = (byte[])msg;
            String data = new String(bytes);
            if(EasyBuffer.notEmpty(data)) {
            	String res = this.handleMsg(data);
            	if(EasyBuffer.notEmpty(res)) {
                    Channel channel = ctx.channel();
                    channel.writeAndFlush(res.getBytes());
            	}
            }
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
 
    /**
     * 没有事件活跃时,主动关闭通道
     */
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            if (e.state() == IdleState.READER_IDLE) {
                ctx.close();
            }
        }
    }
 
    /**
     * 异常处理
     */
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) throws Exception {
        e.printStackTrace();
        ctx.close();
    }
    
    /**
	 * 处理消息
	 * @return
	 */
	public abstract String handleMsg(String msg);
	
	/**
	 * 代码控制是否开启(优先级大于@NettyServer注解)
	 * @return
	 */
	public boolean isOpen() {
		return true;
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy