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

jizcode.netty.server.RtServerHandler Maven / Gradle / Ivy

There is a newer version: 1.0.14-BETA
Show newest version
package jizcode.netty.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.internal.StringUtil;
import jizcode.base.util.JsonUtils;
import jizcode.netty.contract.CmdTable;
import jizcode.netty.contract.RtDataFromClient;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class RtServerHandler extends ChannelInboundHandlerAdapter {
    protected Log logger = LogFactory.getLog(this.getClass());
    /**
     * 客户端与服务端创建连接的时候调用
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ////System.out.println("客户端与服务端连接开始...");
    }

    /**
     * 客户端与服务端断开连接时调用
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        ////System.out.println("客户端与服务端连接关闭...");
    }

    /**
     * 服务端接收客户端发送过来的数据结束之后调用
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
        ////System.out.println("信息接收完毕...");
    }

    /**
     * 工程出现异常的时候调用
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    /**
     * 服务端处理客户端websocket请求的核心方法,这里接收了客户端发来的信息
     */
    @Override
    public void channelRead(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {
        try{
            ////System.out.println("收到客户端的数据:"+msg);
            ////logger.info("收到客户端的数据:"+msg);
            if(msg.equals("HEARTBEAT")){
                return;
            }
            RtDataFromClient data = JsonUtils.fromJson((String)msg,RtDataFromClient.class);
            if(data.getCmd() == CmdTable.Sys_Login && !StringUtil.isNullOrEmpty(data.getOuCode())){
                RtServer.getInstance().addClient(data.getOuCode(), channelHandlerContext.channel());
                ////logger.info("client login:"+data.getOuCode());
            }else{
                Client client = RtServer.getInstance().findClient(data.getOuCode());
                if(client ==null){
                    //System.out.println("can not found client id:"+data.getOuCode());
                }else{
                    //System.out.println("找到客户端");
                    if(!client.response(data)) {
                        RtServer.getInstance().onReceive.apply(client, data);
                    }
                }
            }
        }catch(Exception ex){
            //System.out.println("msg error:"+msg);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy