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.corundumstudio.socketio.handler.EncoderHandler.java

License:Apache License

private void handleWebsocket(final OutPacketMessage msg, ChannelHandlerContext ctx) throws IOException {
    while (true) {
        Queue<Packet> queue = msg.getClientHead().getPacketsQueue(msg.getTransport());
        Packet packet = queue.poll();/*from   w  ww. java2 s  .c o  m*/
        if (packet == null) {
            break;
        }

        final ByteBuf out = encoder.allocateBuffer(ctx.alloc());
        encoder.encodePacket(packet, out, ctx.alloc(), true);

        WebSocketFrame res = new TextWebSocketFrame(out);
        if (log.isTraceEnabled()) {
            log.trace("Out message: {} sessionId: {}", out.toString(CharsetUtil.UTF_8), msg.getSessionId());
        }
        if (out.isReadable()) {
            ctx.channel().writeAndFlush(res);
        } else {
            out.release();
        }

        for (ByteBuf buf : packet.getAttachments()) {
            ByteBuf outBuf = encoder.allocateBuffer(ctx.alloc());
            outBuf.writeByte(4);
            outBuf.writeBytes(buf);
            if (log.isTraceEnabled()) {
                log.trace("Out attachment: {} sessionId: {}", ByteBufUtil.hexDump(outBuf), msg.getSessionId());
            }
            ctx.channel().writeAndFlush(new BinaryWebSocketFrame(outBuf));
        }
    }
}

From source file:com.corundumstudio.socketio.handler.EncoderHandler.java

License:Apache License

private void handleHTTP(OutPacketMessage msg, ChannelHandlerContext ctx) throws IOException {
    Channel channel = ctx.channel();
    Attribute<Boolean> attr = channel.attr(WRITE_ONCE);

    Queue<Packet> queue = msg.getClientHead().getPacketsQueue(msg.getTransport());

    if (!channel.isActive() || queue.isEmpty() || !attr.compareAndSet(null, true)) {
        return;// w  ww.jav a  2  s.co  m
    }

    ByteBuf out = encoder.allocateBuffer(ctx.alloc());
    Boolean b64 = ctx.channel().attr(EncoderHandler.B64).get();
    if (b64 != null && b64) {
        Integer jsonpIndex = ctx.channel().attr(EncoderHandler.JSONP_INDEX).get();
        encoder.encodeJsonP(jsonpIndex, queue, out, ctx.alloc(), 50);
        String type = "application/javascript";
        if (jsonpIndex == null) {
            type = "text/plain";
        }
        sendMessage(msg, channel, out, type);
    } else {
        encoder.encodePackets(queue, out, ctx.alloc(), 50);
        sendMessage(msg, channel, out, "application/octet-stream");
    }
}

From source file:com.corundumstudio.socketio.handler.ResourceHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof FullHttpRequest) {
        FullHttpRequest req = (FullHttpRequest) msg;
        QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());
        URL resUrl = resources.get(queryDecoder.path());
        if (resUrl != null) {
            URLConnection fileUrl = resUrl.openConnection();
            long lastModified = fileUrl.getLastModified();
            // check if file has been modified since last request
            if (isNotModified(req, lastModified)) {
                sendNotModified(ctx);/*from www.j  a v  a2 s  . co  m*/
                req.release();
                return;
            }
            // create resource input-stream and check existence
            final InputStream is = fileUrl.getInputStream();
            if (is == null) {
                sendError(ctx, NOT_FOUND);
                return;
            }
            // create ok response
            HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK);
            // set Content-Length header
            setContentLength(res, fileUrl.getContentLength());
            // set Content-Type header
            setContentTypeHeader(res, fileUrl);
            // set Date, Expires, Cache-Control and Last-Modified headers
            setDateAndCacheHeaders(res, lastModified);
            // write initial response header
            ctx.write(res);

            // write the content stream
            ctx.pipeline().addBefore(SocketIOChannelInitializer.RESOURCE_HANDLER, "chunkedWriter",
                    new ChunkedWriteHandler());
            ChannelFuture writeFuture = ctx.channel().write(new ChunkedStream(is, fileUrl.getContentLength()));
            // add operation complete listener so we can close the channel and the input stream
            writeFuture.addListener(ChannelFutureListener.CLOSE);
            return;
        }
    }
    ctx.fireChannelRead(msg);
}

From source file:com.corundumstudio.socketio.handler.ResourceHandler.java

License:Apache License

private void sendNotModified(ChannelHandlerContext ctx) {
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.NOT_MODIFIED);
    setDateHeader(response);/*from  www .  j a v  a2  s.  co  m*/

    // Close the connection as soon as the error message is sent.
    ctx.channel().write(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:com.corundumstudio.socketio.handler.ResourceHandler.java

License:Apache License

/**
 * Sends an Error response with status message
 *
 * @param ctx/* w  w  w . ja  va 2 s  .  com*/
 * @param status
 */
private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
    HttpHeaders.setHeader(response, CONTENT_TYPE, "text/plain; charset=UTF-8");
    ByteBuf content = Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8);

    ctx.channel().write(response);
    // Close the connection as soon as the error message is sent.
    ctx.channel().write(content).addListener(ChannelFutureListener.CLOSE);
}

From source file:com.corundumstudio.socketio.handler.WrongUrlHandler.java

License:Apache License

public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof FullHttpRequest) {
        FullHttpRequest req = (FullHttpRequest) msg;
        Channel channel = ctx.channel();
        QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());

        HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
        ChannelFuture f = channel.writeAndFlush(res);
        f.addListener(ChannelFutureListener.CLOSE);
        req.release();//w w w .  j  a  va 2s .c om
        log.warn("Blocked wrong socket.io-context request! url: {}, params: {}, ip: {}", queryDecoder.path(),
                queryDecoder.parameters(), channel.remoteAddress());
    }
}

From source file:com.corundumstudio.socketio.SocketIOEncoder.java

License:Apache License

private void write(HttpMessage xhrMessage, Packet packet, ChannelHandlerContext ctx, ByteBuf out)
        throws IOException {
    XHRClientEntry clientEntry = getXHRClientEntry(xhrMessage.getSessionId());
    if (packet != null) {
        clientEntry.addPacket(packet);//  w w w .  j a  v  a  2  s  .c o m
    }

    Channel channel = ctx.channel();
    if (!channel.isActive() || clientEntry.getPackets().isEmpty() || !clientEntry.writeOnce(channel)) {
        out.release();
        return;
    }

    encoder.encodePackets(clientEntry.getPackets(), out, ctx.alloc());
    sendMessage(xhrMessage, channel, out);
}

From source file:com.corundumstudio.socketio.SocketIOEncoder.java

License:Apache License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (!(msg instanceof BaseMessage)) {
        super.write(ctx, msg, promise);
        return;//  w  ww . java  2  s.  c  o m
    }

    ByteBuf out = encoder.allocateBuffer(ctx.alloc());

    if (msg instanceof AuthorizeMessage) {
        handle((AuthorizeMessage) msg, ctx.channel(), out);
    }

    if (msg instanceof XHRNewChannelMessage) {
        write((XHRNewChannelMessage) msg, null, ctx, out);
    }
    if (msg instanceof XHRPacketMessage) {
        XHRPacketMessage m = (XHRPacketMessage) msg;
        write(m, m.getPacket(), ctx, out);
    }
    if (msg instanceof XHROutMessage) {
        sendMessage((XHROutMessage) msg, ctx.channel(), out);
    }
    if (msg instanceof XHRErrorMessage) {
        XHRErrorMessage xhrErrorMessage = (XHRErrorMessage) msg;
        encoder.encodePacket(xhrErrorMessage.getPacket(), out);
        sendMessage(xhrErrorMessage, ctx.channel(), out);
    }

    if (msg instanceof WebSocketPacketMessage) {
        handle((WebSocketPacketMessage) msg, ctx.channel(), out);
    }
    if (msg instanceof WebsocketErrorMessage) {
        handle((WebsocketErrorMessage) msg, ctx.channel(), out);
    }
}

From source file:com.corundumstudio.socketio.transport.PollingTransport.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof FullHttpRequest) {
        FullHttpRequest req = (FullHttpRequest) msg;
        QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());

        List<String> transport = queryDecoder.parameters().get("transport");

        if (transport != null && NAME.equals(transport.get(0))) {
            List<String> sid = queryDecoder.parameters().get("sid");
            List<String> j = queryDecoder.parameters().get("j");
            List<String> b64 = queryDecoder.parameters().get("b64");

            String origin = req.headers().get(HttpHeaders.Names.ORIGIN);
            ctx.channel().attr(EncoderHandler.ORIGIN).set(origin);

            String userAgent = req.headers().get(HttpHeaders.Names.USER_AGENT);
            ctx.channel().attr(EncoderHandler.USER_AGENT).set(userAgent);

            if (j != null && j.get(0) != null) {
                Integer index = Integer.valueOf(j.get(0));
                ctx.channel().attr(EncoderHandler.JSONP_INDEX).set(index);
            }/*from ww w .j  a  v  a 2  s  . c  om*/
            if (b64 != null && b64.get(0) != null) {
                Integer enable = Integer.valueOf(b64.get(0));
                ctx.channel().attr(EncoderHandler.B64).set(enable == 1);
            }

            try {
                if (sid != null && sid.get(0) != null) {
                    final UUID sessionId = UUID.fromString(sid.get(0));
                    handleMessage(req, sessionId, queryDecoder, ctx);
                } else {
                    // first connection
                    ClientHead client = ctx.channel().attr(ClientHead.CLIENT).get();
                    handleMessage(req, client.getSessionId(), queryDecoder, ctx);
                }
            } finally {
                req.release();
            }
            return;
        }
    }
    ctx.fireChannelRead(msg);
}

From source file:com.corundumstudio.socketio.transport.PollingTransport.java

License:Apache License

private void handleMessage(FullHttpRequest req, UUID sessionId, QueryStringDecoder queryDecoder,
        ChannelHandlerContext ctx) throws IOException {
    String origin = req.headers().get(HttpHeaders.Names.ORIGIN);
    if (queryDecoder.parameters().containsKey("disconnect")) {
        ClientHead client = clientsBox.get(sessionId);
        client.onChannelDisconnect();//from   w w  w.  jav a2  s .  c om
        ctx.channel().writeAndFlush(new XHRPostMessage(origin, sessionId));
    } else if (HttpMethod.POST.equals(req.getMethod())) {
        onPost(sessionId, ctx, origin, req.content());
    } else if (HttpMethod.GET.equals(req.getMethod())) {
        onGet(sessionId, ctx, origin);
    } else if (HttpMethod.OPTIONS.equals(req.getMethod())) {
        onOptions(sessionId, ctx, origin);
    } else {
        log.error("Wrong {} method invocation for {}", req.getMethod(), sessionId);
        sendError(ctx);
    }
}