Example usage for io.netty.channel ChannelHandlerContext channel

List of usage examples for io.netty.channel ChannelHandlerContext channel

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext channel.

Prototype

Channel channel();

Source Link

Document

Return the Channel which is bound to the ChannelHandlerContext .

Usage

From source file:com.dh.netty.NettyServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, NettyMessageVO nettyMessageVO) throws Exception {

    if (nettyMessageVO == null) {
        return;/*from w w w. j av a2s .com*/
    }

    nettyMessageVO.setChannel(ctx.channel());

    int playerid = ServerHandler.get(ctx.channel());
    if (playerid > 0) {
        UserCached userCached = ServerHandler.getUserCached(playerid);
        if (userCached != null) {
            userCached.setLastedAccessTime(System.currentTimeMillis());
        }
    }

    int CSCommondCode = nettyMessageVO.getCommandCode();
    if (CSCommondCode < 1000 || CSCommondCode >= 10000) {
        try {
            gmService.addBlackIP(GameUtil.getIpString(ctx.channel().remoteAddress().toString()),
                    GameUtil.getIpString(ctx.channel().remoteAddress().toString()),
                    "?", BLOCK_ENUM.BLOCK_IP_VALUE);
            logger.error("?:" + CSCommondCode + "IP(" + ctx.channel().remoteAddress()
                    + "),???");
            ctx.channel().close();
            return;
        } catch (Exception e) {
            logger.error(Tool.concatString("ip?", e.getCause()), e);
            return;
        }
    }

    if (Tool.between(nettyMessageVO.getCommandCode(), 1100, 1199)) { // 100
        GMCommandQueue.getInstance().put(nettyMessageVO);
        return;
    }

    if (LanjieTool.lanjie(nettyMessageVO)) {
        try {
            gmService.addBlackIP(GameUtil.getIpString(nettyMessageVO.getChannel().remoteAddress().toString()),
                    GameUtil.getIpString(nettyMessageVO.getChannel().remoteAddress().toString()),
                    "?", BLOCK_ENUM.BLOCK_ACC_IP_VALUE);
            logger.error("?:" + CSCommondCode + "IP(" + ctx.channel().remoteAddress()
                    + "),???");
            ctx.channel().close();
            return;
        } catch (Exception e) {
            ;
            logger.error(Tool.concatString("ip?", e.getCause()), e);
            return;
        }
    }

    if (System_status == 1) {
        return;
    }

    if (nettyMessageVO.getCommandCode() < 100) { // 100
        LocalCommandQueue.getInstance().put(nettyMessageVO);
    } else if (Tool.between(nettyMessageVO.getCommandCode(), 9800, 9899)) {
        LocalCommandQueue.getInstance().put(nettyMessageVO);
    } else if (Tool.between(nettyMessageVO.getCommandCode(), 2100, 2299)) {
        ChatCommandQueue.getInstance().put(nettyMessageVO);
    } else {
        int n = ArrayCommandQueue.getMod(nettyMessageVO.getChannel().hashCode());
        ArrayCommandQueue.arrQueue[n].put(nettyMessageVO);
    }
    // else if (nettyMessageVO.getCommandCode() >= 9800 &&
    // nettyMessageVO.getCommandCode() <= 9899) {
    // LoginCommandQueue.getInstance().put(nettyMessageVO);
    // } else if (nettyMessageVO.getCommandCode() >= 9000 &&
    // nettyMessageVO.getCommandCode() <= 9099) { // ??
    // // int userid = ServerHandler.get(nettyMessageVO.getChannel());
    // // nettyMessageVO.setUserid(userid);
    // LocalCommandQueue.getInstance().put(nettyMessageVO);
    // } else if (nettyMessageVO.getCommandCode() >= 5000 &&
    // nettyMessageVO.getCommandCode() <= 5099) {// 
    // MoveCommandQueue.getInstance().put(nettyMessageVO);
    // } else {
    // // if (mode == MODE_NORMAL) {
    // // processMsg(nettyMessageVO);
    // // } else if (specialProcessor(nettyMessageVO)) {
    // //
    // // } else {
    // // logger.debug("");
    // // }
    // LocalCommandQueue.getInstance().put(nettyMessageVO);
    // }

}

From source file:com.dh.netty.NettyServerHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    logger.debug(Tool.concatString("", ctx.channel().remoteAddress(), "-->>"));
    try {//w w  w. ja  v a  2 s. co m
        if (GMConstants.isBlackIP(GameUtil.getIpString(ctx.channel().remoteAddress().toString()))) {
            ctx.channel().close();
        }
    } catch (Exception e) {
        logger.error(Tool.concatString("ip?", e.getCause()), e);
    }
    super.channelActive(ctx);
}

From source file:com.dh.netty.NettyServerHandler.java

License:Apache License

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    // ServerHandler.removePlayerChannelByChannel(ctx.channel());
    int playerid = ServerHandler.get(ctx.channel());
    System.out.println(Tool.concatString("(playerId=", playerid, ")"));
    if (playerid > 0) {
        UserCached userCached = ServerHandler.getUserCached(playerid);
        playerTimerService.addOnlineReward(userCached);
        playerTimerService.flushKnaspack(userCached);
        userCached.getPlayerVO().setIs_online(0);
        playerService.updatePlayerOnline(userCached.getPlayerVO());
        ServerHandler.removeBossChannel(ctx.channel());
        ServerHandler.removeFromLegionChannel(userCached.getPlayerVO().getLegionId(), ctx.channel());
    }//from   w  ww.  j a  va 2  s .com

    LanjieTool.clear(ctx.channel().remoteAddress().toString());
    // // ?
    // if (userCached != null && userCached.getChannelGroup() != null) {
    // areaGroupService.areaLeaveBroadcast(userCached.getChannelGroup(),
    // userCached.getChannel(), playerid);
    // areaGroupService.clearChannel(userCached.getChannelGroup(),
    // userCached.getChannel());
    //
    // // ?? ?
    // userCached.getPlayerStrongHoldVO().setPosx(AreaOperationHandler.START_POS_X);
    // userCached.getPlayerStrongHoldVO().setPosy(AreaOperationHandler.START_POS_Y);
    // userCached.setChannelGroup(null);
    // }
    // }
    super.channelInactive(ctx);
}

From source file:com.digisky.innerproxy.server.InnerProxyHttpServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
    LogMgr.debug("channelRead0()", "channelRead0");
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        if (HttpHeaders.is100ContinueExpected(request)) {
            send100Continue(ctx);/* ww  w.  j  a  v a 2s.c o m*/
        }
    }
    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;
        ByteBuf content = httpContent.content();
        LogMgr.debug(InnerProxyHttpServerHandler.class.getName(),
                "content:" + content.toString(CharsetUtil.UTF_8));
        String jsonmsg = null;
        try {
            jsonmsg = java.net.URLDecoder.decode(content.toString(CharsetUtil.UTF_8), "utf-8");
        } catch (UnsupportedEncodingException e) {
            LogMgr.warn("", "URLDecoder exceptionn caught.");
            // e.printStackTrace();
        }
        if (msgCheck(jsonmsg) == false) { //contain ';', bad.
            LogMgr.error(InnerProxyHttpServerHandler.class.getName(),
                    "jsonmsg contain ; or ', close it. peer info:" + ctx.channel().remoteAddress().toString());
            ctx.channel().close();
            return;
        }
        LogMgr.debug(InnerProxyHttpServerHandler.class.getName(), "jsonmsg:" + jsonmsg);
        LogMgr.debug(InnerProxyHttpServerHandler.class.getName(), "uri:" + request.getUri());
        LogMgr.debug(InnerProxyHttpServerHandler.class.getName(), "method:" + request.getMethod());
        String type = request.getUri().split("/")[1];
        if (type.equals("email_activate") == true) { // GET?
            String[] tmp = request.getUri().split("=");
            String acode = tmp[tmp.length - 1];
            LogMgr.debug(InnerProxyHttpServerHandler.class.getName(), "acode:" + acode);
            ProcessServerManager.getInstance().process(ctx.channel(), type, "{\"acode\":\"" + acode + "\"}");
        } else { //POST
            LogMgr.debug(InnerProxyHttpServerHandler.class.getName(), "type:" + type);
            // ugly code
            ProcessServerManager.getInstance().process(ctx.channel(), type, jsonmsg.replace("val=", ""));
        }
    }
}

From source file:com.digisky.innerproxy.server.InnerProxyHttpServerHandler.java

License:Apache License

@Override
public void channelRegistered(ChannelHandlerContext ctx) {
    LogMgr.debug("", "channelRegistered called. peer ip_port:" + ctx.channel().remoteAddress());
}

From source file:com.digisky.innerproxy.server.InnerProxyHttpServerHandler.java

License:Apache License

public void channelUnregistered(ChannelHandlerContext ctx) {
    LogMgr.debug("", "channelUnregistered called. peer ip_port:" + ctx.channel().remoteAddress());
}

From source file:com.digisky.outerproxy.server.OuterProxyHttpServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
    LogMgr.debug("channelRead0()", "channelRead0");
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        if (HttpHeaders.is100ContinueExpected(request)) {
            send100Continue(ctx);//w  ww  .  ja  v  a  2  s.com
        }
    }
    if (msg instanceof HttpContent) {
        String type = request.getUri().split("/")[1];
        if (type.equals("email_activate") == true) { // GET?
            String[] tmp = request.getUri().split("=");
            String acode = tmp[tmp.length - 1];
            LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "acode:" + acode);
            ProcessServerManager.getInstance().process(ctx.channel(), type, "{\"acode\":\"" + acode + "\"}");
            return;
        } else if (type.equals("email_pwd_reset") == true) { //?
            String[] tmp = request.getUri().split("=");
            String vcode = tmp[tmp.length - 1];
            LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "acode:" + vcode);
            ProcessServerManager.getInstance().process(ctx.channel(), type, "{\"vcode\":\"" + vcode + "\"}");
            return;
        }

        //email_active  email_pwd_reset, 
        //???
        HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(request);
        InterfaceHttpData postData = decoder.getBodyHttpData("val");
        if (postData instanceof FileUpload == false) {//outerProxy????
            ctx.close();
            return;
        }
        FileUpload binData = (FileUpload) postData;
        ByteBuf content = null;
        try {
            content = binData.getByteBuf();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //content??. , 0. ?(head)?id, json?, ?. ??, ???. 
        //?content?head
        int index = content.bytesBefore((byte) 0);
        if (index < 0) {
            LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "ellegal request.");
            ctx.channel().close();
            return;
        }
        byte[] head = new byte[index];
        content.readBytes(head);
        String strHead = new String(head);
        LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "head:" + strHead);
        JSONObject jo = JSONObject.parseObject(strHead);
        LogMgr.debug(OuterProxyHttpServerHandler.class.getName(),
                "jo::app_id:" + jo.getString("app_id") + " jo::version:" + jo.getString("version"));
        content.readByte();//0

        //?content?tail
        byte[] tail = new byte[content.readableBytes()];
        content.readBytes(tail);
        String sjsonmsg = null;
        if (jo.getString("version").equals("0")) { //?0
            byte[] bjsonmsg = XXTEA.decrypt(tail, key);
            int data_len = bjsonmsg.length;
            for (int i = bjsonmsg.length - 1; i != 0; --i) {
                if (bjsonmsg[i] == 0) {
                    data_len--;
                    continue;
                } else {
                    break;
                }
            }
            try {
                sjsonmsg = new String(bjsonmsg, 0, data_len, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else { //TODO?0, app_id. ???
            LogMgr.error(OuterProxyHttpServerHandler.class.getName(),
                    "?0, ??");
            ctx.close();
            return;
        }
        sjsonmsg = sjsonmsg.substring(sjsonmsg.indexOf('{'), sjsonmsg.indexOf('}') + 1);//?
        LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "sjson:" + sjsonmsg);

        //debug code
        //JSONObject jsonObj = JSONObject.parseObject(sjsonmsg);
        //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "tmp.get:" + jsonObj.getString("model"));

        /* debug code
        //b.getBytes(n+1, tail, 0, b.g-n-1);
        for(int i=0; i< tail.length; ++i) {
           System.out.print(String.format("%x ", tail[i]));
        }
        */

        //debug code
        //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "uri:" + request.getUri());
        //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(),"method:" + request.getMethod());
        //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(),"type:" + type);
        LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "json:" + sjsonmsg);

        //
        ProcessServerManager.getInstance().process(ctx.channel(), type, sjsonmsg);
    }
}

From source file:com.digisky.stresstest.HttpSnoopClientHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    System.out.println("channelActive");
    test(ctx.channel(), "normal_login", R_normal_login.j_username);
}

From source file:com.digitalpetri.modbus.slave.ModbusTcpSlave.java

License:Apache License

private void onChannelRead(ChannelHandlerContext ctx, ModbusTcpPayload payload) {
    ServiceRequestHandler handler = requestHandler.get();
    if (handler == null)
        return;/* www . j ava2  s.c om*/

    switch (payload.getModbusPdu().getFunctionCode()) {
    case ReadCoils:
        handler.onReadCoils(ModbusTcpServiceRequest.of(payload, ctx.channel()));
        break;

    case ReadDiscreteInputs:
        handler.onReadDiscreteInputs(ModbusTcpServiceRequest.of(payload, ctx.channel()));
        break;

    case ReadHoldingRegisters:
        handler.onReadHoldingRegisters(ModbusTcpServiceRequest.of(payload, ctx.channel()));
        break;

    case ReadInputRegisters:
        handler.onReadInputRegisters(ModbusTcpServiceRequest.of(payload, ctx.channel()));
        break;

    case WriteSingleCoil:
        handler.onWriteSingleCoil(ModbusTcpServiceRequest.of(payload, ctx.channel()));
        break;

    case WriteSingleRegister:
        handler.onWriteSingleRegister(ModbusTcpServiceRequest.of(payload, ctx.channel()));
        break;

    case WriteMultipleCoils:
        handler.onWriteMultipleCoils(ModbusTcpServiceRequest.of(payload, ctx.channel()));
        break;

    case WriteMultipleRegisters:
        handler.onWriteMultipleRegisters(ModbusTcpServiceRequest.of(payload, ctx.channel()));
        break;

    case MaskWriteRegister:
        handler.onMaskWriteRegister(ModbusTcpServiceRequest.of(payload, ctx.channel()));
        break;

    default:
        /* Function code not currently supported */
        ExceptionResponse response = new ExceptionResponse(payload.getModbusPdu().getFunctionCode(),
                ExceptionCode.IllegalFunction);

        ctx.writeAndFlush(new ModbusTcpPayload(payload.getTransactionId(), payload.getUnitId(), response));
        break;
    }
}

From source file:com.digitalpetri.modbus.slave.ModbusTcpSlave.java

License:Apache License

private void onChannelInactive(ChannelHandlerContext ctx) {
    logger.debug("Master/client channel closed: {}", ctx.channel());
}