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.fanavard.challenge.server.websocket.server.WebSocketServerHandler.java

License:Apache License

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

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

    // Send the demo page and favicon.ico
    if ("/".equals(req.uri())) {
        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");
        HttpHeaderUtil.setContentLength(res, content.readableBytes());

        sendHttpResponse(ctx, req, res);
        return;
    }
    if ("/favicon.ico".equals(req.uri())) {
        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:com.fanavard.challenge.server.websocket.server.WebSocketServerHandler.java

License:Apache License

private void handleWebSocketFrame(final ChannelHandlerContext ctx, WebSocketFrame frame) {

    // Check for closing frame
    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        return;//from ww w  .j  a v  a2 s  .c o  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()));
    }

    // Send the uppercase string back.
    final String request = ((TextWebSocketFrame) frame).text();
    System.err.printf("%s received %s%n", ctx.channel(), request);
    //        ctx.channel().write(new TextWebSocketFrame("" + new Date()));
    ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
    //        new Thread(new Runnable() {
    //            @Override
    //            public void run() {
    //                for (int i = 0; i < 5; i ++) {
    //                    ctx.channel().flush();
    //                    try {
    //                        Thread.sleep(1000);
    //                    } catch (InterruptedException e) {
    //                        e.printStackTrace();
    //                    }
    //                }
    //
    //            }
    //        }).start();
}

From source file:com.fanavard.challenge.server.websocket.server.WebSocketServerHandler.java

License:Apache License

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.status().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);/*from  w  w w  .  j  a  va  2s . com*/
        buf.release();
        HttpHeaderUtil.setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpHeaderUtil.isKeepAlive(req) || res.status().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.farsunset.cim.sdk.android.CIMConnectorManager.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {

    setLastHeartbeatTime(ctx.channel());

    Intent intent = new Intent();
    intent.setAction(CIMConstant.IntentAction.ACTION_CONNECTION_SUCCESSED);
    context.sendBroadcast(intent);//from  w  w w . j  ava2  s  .  com

}

From source file:com.farsunset.cim.sdk.android.CIMConnectorManager.java

License:Apache License

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {

    /**// ww w .ja  v a  2s.c  o  m
     * wifi??? ???
     * 
     */
    if (evt instanceof IdleStateEvent && ((IdleStateEvent) evt).state().equals(IdleState.READER_IDLE)) {
        Long lastTime = getLastHeartbeatTime(ctx.channel());
        if (lastTime != null && System.currentTimeMillis() - lastTime > HEARBEAT_TIME_OUT) {
            channel.close();
        }
    }

}

From source file:com.farsunset.cim.sdk.android.CIMConnectorManager.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof Message) {

        Intent intent = new Intent();
        intent.setAction(CIMConstant.IntentAction.ACTION_MESSAGE_RECEIVED);
        intent.putExtra(Message.class.getName(), (Message) msg);
        context.sendBroadcast(intent);// w  w w .  j  ava  2s.c o m

    }
    if (msg instanceof ReplyBody) {

        Intent intent = new Intent();
        intent.setAction(CIMConstant.IntentAction.ACTION_REPLY_RECEIVED);
        intent.putExtra(ReplyBody.class.getName(), (ReplyBody) msg);
        context.sendBroadcast(intent);
    }

    // ????
    if (msg instanceof HeartbeatRequest) {
        ctx.writeAndFlush(HeartbeatResponse.getInstance());
        setLastHeartbeatTime(ctx.channel());
    }

}

From source file:com.farsunset.cim.sdk.android.filter.CIMLoggingHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    if (debug) {/*  ww  w.  j a v a  2  s. c  o  m*/
        Log.i(TAG, "OPENED" + getSessionInfo(ctx.channel()));
    }
    ctx.fireChannelActive();
}

From source file:com.farsunset.cim.sdk.android.filter.CIMLoggingHandler.java

License:Apache License

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    if (debug) {//from ww  w .  j  a v a 2 s  .c  o m
        Log.i(TAG, "CLOSED" + getSessionInfo(ctx.channel()));
    }
    ctx.fireChannelInactive();
}

From source file:com.farsunset.cim.sdk.android.filter.CIMLoggingHandler.java

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

    if (debug) {/*  w w w .  j av a2  s  . co m*/
        Log.d(TAG, String.format("EXCEPTION" + getSessionInfo(ctx.channel()) + "\n%s",
                cause.getClass().getName() + ":" + cause.getMessage()));
    }

    ctx.channel().close();
}

From source file:com.farsunset.cim.sdk.android.filter.CIMLoggingHandler.java

License:Apache License

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (debug && evt instanceof IdleStateEvent) {
        Log.d(TAG, String.format("IDLE %s" + getSessionInfo(ctx.channel()),
                ((IdleStateEvent) evt).state().toString()));
    }//from  w  ww. j  a  v  a2  s . c o  m
    ctx.fireUserEventTriggered(evt);
}