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:cn.link.lis.LIPServerHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    super.channelActive(ctx);
    recipients.add(ctx.channel());
    Message msg = mHandler.obtainMessage(MainActivity.SERVER_CLIENT_CONNECTED,
            ctx.channel().remoteAddress().toString());
    mHandler.sendMessage(msg);//from  w  w w.j  ava  2s .  com

}

From source file:cn.link.lis.LIPServerHandler.java

License:Apache License

@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
    super.channelUnregistered(ctx);
    try {//from  w  w w . j  a v  a  2s. com
        recipients.remove(ctx.channel());
        System.out.println("channel?" + recipients.size());
    } catch (Exception ex) {
        System.out.println("channel" + ex.getMessage());
    }
}

From source file:cn.link.lis.LIPServerHandler.java

License:Apache License

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    super.channelInactive(ctx);
    try {//from w w  w  .j  a  v  a 2s .c  om
        recipients.remove(ctx.channel());
        System.out.println("channel?" + recipients.size());
    } catch (Exception ex) {
        System.out.println("channel" + ex.getMessage());
    }
}

From source file:cn.npt.net.handler.BaseWebSocketClientHandler.java

License:Apache License

@Override
public void channelInactive(ChannelHandlerContext ctx) {
    log.info("WebSocket Client disconnected to " + ctx.channel());
}

From source file:cn.npt.net.handler.BaseWebSocketClientHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        log.info("WebSocket Client connected to " + ctx.channel());
        handshakeFuture.setSuccess();//w ww  . ja v  a  2s  .  c  om
        return;
    }

    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new IllegalStateException("Unexpected FullHttpResponse (getStatus=" + response.getStatus()
                + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
    }

    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
        TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
        doReceive(textFrame.text());
    } else if (frame instanceof PongWebSocketFrame) {
        //System.out.println("WebSocket Client received pong");
    } else if (frame instanceof CloseWebSocketFrame) {
        log.info("WebSocket Client received closing");
        ch.close();
    }
}

From source file:cn.npt.net.websocket.WebSocketServerHandler.java

License:Apache License

@Override
public void channelInactive(ChannelHandlerContext ctx) {
    this.timer.cancel();
    this.timer = null;
    log.info(ctx.channel() + " websocket disconnected!");
    ctx.close();/*  ww w .  jav a 2 s . c  om*/
}

From source file:cn.npt.net.websocket.WebSocketServerHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) {
    this.timer = new Timer();
    log.info(ctx.channel() + " websocket connected!");
}

From source file:cn.npt.net.websocket.WebSocketServerHandler.java

License:Apache License

private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
    // Handle a bad request.
    if (!req.getDecoderResult().isSuccess()) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
        return;//from  w  w  w  . j a  v  a2s  . c  o m
    }

    // Allow only GET methods.
    if (req.getMethod() != GET) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
        return;
    }

    // Send the demo page and favicon.ico
    if ("/".equals(req.getUri())) {
        ByteBuf content = WebSocketServerIndexPage.getContent(getWebSocketLocation(req));
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);

        res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
        HttpHeaders.setContentLength(res, content.readableBytes());

        sendHttpResponse(ctx, req, res);
        return;
    }
    if ("/favicon.ico".equals(req.getUri())) {
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND);
        sendHttpResponse(ctx, req, res);
        return;
    }

    // Handshake
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
            null, true);
    handshaker = wsFactory.newHandshaker(req);
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {
        handshaker.handshake(ctx.channel(), req);
    }
}

From source file:cn.npt.net.websocket.WebSocketServerHandler.java

License:Apache License

private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

    // Check for closing frame
    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        return;//from  ww w .ja  v  a 2 s.co  m
    }
    if (frame instanceof PingWebSocketFrame) {
        ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
        return;
    }
    if (!(frame instanceof TextWebSocketFrame)) {
        throw new UnsupportedOperationException(
                String.format("%s frame types not supported", frame.getClass().getName()));
    }

    //??{cmd:getSensorValue,depth:0,timeInterval:1000,sensorIds:[...]},?????
    String request = ((TextWebSocketFrame) frame).text();
    JSONObject reqObj = JSON.parseObject(request);
    if (reqObj.containsKey("cmd")) {
        String cmd = reqObj.getString("cmd");
        switch (cmd) {
        case "getStartTime":
            getStartTime(ctx);
            break;
        case "getSensorCount":
            getSensorCount(ctx);
            break;
        case "getSensorValue"://?
            getSensorValue(reqObj, ctx);
            break;
        case "updateSensorValue"://?
            updateSensorValue(reqObj, ctx);
            break;
        case "getCachePoolDepth":
            getCachePoolDepth(reqObj, ctx);
            break;
        case "getSensorHandlers":
            getSensorHandlers(reqObj, ctx);
            break;
        default:
            ctx.writeAndFlush(new TextWebSocketFrame(""));
            break;
        }
    } else {
        log.warn("unknown command");
        ctx.writeAndFlush(new TextWebSocketFrame("?"));
    }

    //ctx.executor().scheduleAtFixedRate(paramRunnable, paramLong1, paramLong2, paramTimeUnit)

}

From source file:cn.savor.small.netty.MiniProNettyClientHandler.java

License:Open Source License

@Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
        String channelId = ctx.channel().id().toString();
        if (evt instanceof IdleStateEvent) {

            IdleStateEvent event = (IdleStateEvent) evt;

            if (event.state().equals(IdleState.READER_IDLE)) {
                //?
                LogUtils.i("READER_IDLE");
                LogFileUtil.write("MiniNettyClientHandler READER_IDLE");

            } else if (event.state().equals(IdleState.WRITER_IDLE)) {

                LogUtils.i("WRITER_IDLE");
                LogFileUtil.write("MiniNettyClientHandler WRITER_IDLE");
                try {
                    // ???
                    MessageBean message = new MessageBean();
                    message.setCmd(MessageBean.Action.HEART_CLENT_TO_SERVER);
                    String number = channelId + System.currentTimeMillis();
                    message.setSerialnumber(number);
                    message.setIp(AppUtils.getLocalIPAddress());
                    message.setMac(session.getEthernetMac());
                    InnerBean bean = new InnerBean();
                    bean.setHotelId(session.getBoiteId());
                    bean.setRoomId(session.getRoomId());
                    bean.setSsid(AppUtils.getShowingSSID(mContext));
                    bean.setBoxId(session.getBoxId());
                    ArrayList<String> contList = new ArrayList<>();
                    contList.add("I am a mini Heart Pakage...");
                    contList.add(new Gson().toJson(bean));
                    message.setContent(contList);
                    ChannelFuture future = ctx.writeAndFlush(message);
                    if (!future.isSuccess()) {
                        close(ctx);//w  w  w .  ja  v  a  2 s.  com
                    }
                    LogUtils.v("miniProgram--WRITER_IDLE====" + channelId + "====>>>>...??:"
                            + message.getSerialnumber());
                    LogUtils.v("miniProgram--future.isSuccess()====" + future.isSuccess());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (event.state().equals(IdleState.ALL_IDLE)) {
                //
                //?REQ==========
                LogUtils.i("ALL_IDLE");
                close(ctx);
            }

        }
    }