Search in sources :

Example 26 with CloseWebSocketFrame

use of io.netty.handler.codec.http.websocketx.CloseWebSocketFrame in project carbon-apimgt by wso2.

the class WebsocketInboundHandler method channelRead.

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    String channelId = ctx.channel().id().asLongText();
    // This block is for the health check of the ports 8099 and 9099
    if (msg instanceof FullHttpRequest && ((FullHttpRequest) msg).headers() != null && !((FullHttpRequest) msg).headers().contains(HttpHeaders.UPGRADE) && ((FullHttpRequest) msg).uri().equals(APIConstants.WEB_SOCKET_HEALTH_CHECK_PATH)) {
        ctx.fireChannelRead(msg);
        return;
    }
    InboundMessageContext inboundMessageContext;
    if (InboundMessageContextDataHolder.getInstance().getInboundMessageContextMap().containsKey(channelId)) {
        inboundMessageContext = InboundMessageContextDataHolder.getInstance().getInboundMessageContextForConnectionId(channelId);
    } else {
        inboundMessageContext = new InboundMessageContext();
        InboundMessageContextDataHolder.getInstance().addInboundMessageContextForConnection(channelId, inboundMessageContext);
    }
    inboundMessageContext.setUserIP(getRemoteIP(ctx));
    if (APIUtil.isAnalyticsEnabled()) {
        WebSocketUtils.setApiPropertyToChannel(ctx, org.wso2.carbon.apimgt.gateway.handlers.analytics.Constants.REQUEST_START_TIME_PROPERTY, System.currentTimeMillis());
        WebSocketUtils.setApiPropertyToChannel(ctx, org.wso2.carbon.apimgt.gateway.handlers.analytics.Constants.USER_IP_PROPERTY, inboundMessageContext.getUserIP());
    }
    // check if the request is a handshake
    if (msg instanceof FullHttpRequest) {
        FullHttpRequest req = (FullHttpRequest) msg;
        populateContextHeaders(req, inboundMessageContext);
        InboundProcessorResponseDTO responseDTO = webSocketProcessor.handleHandshake(req, ctx, inboundMessageContext);
        if (!responseDTO.isError()) {
            setApiAuthPropertiesToChannel(ctx, inboundMessageContext);
            if (StringUtils.isNotEmpty(inboundMessageContext.getToken())) {
                req.headers().set(APIMgtGatewayConstants.WS_JWT_TOKEN_HEADER, inboundMessageContext.getToken());
            }
            ctx.fireChannelRead(req);
            publishHandshakeEvent(ctx, inboundMessageContext);
            InboundWebsocketProcessorUtil.publishGoogleAnalyticsData(inboundMessageContext, ctx.channel().remoteAddress().toString());
        } else {
            InboundMessageContextDataHolder.getInstance().removeInboundMessageContextForConnection(channelId);
            FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(responseDTO.getErrorCode()), Unpooled.copiedBuffer(responseDTO.getErrorMessage(), CharsetUtil.UTF_8));
            httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
            httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, httpResponse.content().readableBytes());
            ctx.writeAndFlush(httpResponse);
        }
    } else if ((msg instanceof CloseWebSocketFrame) || (msg instanceof PingWebSocketFrame)) {
        // remove inbound message context from data holder
        InboundMessageContextDataHolder.getInstance().getInboundMessageContextMap().remove(channelId);
        // if the inbound frame is a closed frame, throttling, analytics will not be published.
        ctx.fireChannelRead(msg);
    } else if (msg instanceof WebSocketFrame) {
        InboundProcessorResponseDTO responseDTO = webSocketProcessor.handleRequest((WebSocketFrame) msg, inboundMessageContext);
        if (responseDTO.isError()) {
            if (responseDTO.isCloseConnection()) {
                // remove inbound message context from data holder
                InboundMessageContextDataHolder.getInstance().getInboundMessageContextMap().remove(channelId);
                if (log.isDebugEnabled()) {
                    log.debug("Error while handling Outbound Websocket frame. Closing connection for " + ctx.channel().toString());
                }
                ctx.writeAndFlush(new CloseWebSocketFrame(responseDTO.getErrorCode(), responseDTO.getErrorMessage() + StringUtils.SPACE + "Connection closed" + "!"));
                ctx.close();
            } else {
                String errorMessage = responseDTO.getErrorResponseString();
                ctx.writeAndFlush(new TextWebSocketFrame(errorMessage));
                if (responseDTO.getErrorCode() == WebSocketApiConstants.FrameErrorConstants.THROTTLED_OUT_ERROR) {
                    if (log.isDebugEnabled()) {
                        log.debug("Inbound Websocket frame is throttled. " + ctx.channel().toString());
                    }
                    publishPublishThrottledEvent(ctx);
                }
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Sending Inbound Websocket frame." + ctx.channel().toString());
            }
            ctx.fireChannelRead(msg);
            // publish analytics events if analytics is enabled
            publishPublishEvent(ctx);
        }
    }
}
Also used : CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) InboundProcessorResponseDTO(org.wso2.carbon.apimgt.gateway.inbound.websocket.InboundProcessorResponseDTO) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) InboundMessageContext(org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) WebSocketFrame(io.netty.handler.codec.http.websocketx.WebSocketFrame) PingWebSocketFrame(io.netty.handler.codec.http.websocketx.PingWebSocketFrame) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) PingWebSocketFrame(io.netty.handler.codec.http.websocketx.PingWebSocketFrame)

Example 27 with CloseWebSocketFrame

use of io.netty.handler.codec.http.websocketx.CloseWebSocketFrame in project ballerina by ballerina-lang.

the class WebSocketRemoteServerFrameHandler method channelRead0.

@Override
protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
    if (frame instanceof TextWebSocketFrame) {
        // Echos the same text
        String text = ((TextWebSocketFrame) frame).text();
        if (PING.equals(text)) {
            ctx.channel().writeAndFlush(new PingWebSocketFrame(Unpooled.wrappedBuffer(ByteBuffer.wrap(new byte[] { 1, 2, 3, 4, 5 }))));
            return;
        }
        ctx.channel().writeAndFlush(new TextWebSocketFrame(text));
    } else if (frame instanceof CloseWebSocketFrame) {
        ctx.close();
        isOpen = false;
    } else {
        String message = "unsupported frame type: " + frame.getClass().getName();
        throw new UnsupportedOperationException(message);
    }
}
Also used : CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) PingWebSocketFrame(io.netty.handler.codec.http.websocketx.PingWebSocketFrame)

Example 28 with CloseWebSocketFrame

use of io.netty.handler.codec.http.websocketx.CloseWebSocketFrame in project ballerina by ballerina-lang.

the class WebSocketClient method shutDown.

/**
 * Shutdown the WebSocket Client.
 */
public void shutDown() throws InterruptedException {
    channel.writeAndFlush(new CloseWebSocketFrame());
    channel.closeFuture().sync();
    group.shutdownGracefully();
}
Also used : CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame)

Example 29 with CloseWebSocketFrame

use of io.netty.handler.codec.http.websocketx.CloseWebSocketFrame in project ballerina by ballerina-lang.

the class WebSocketClientHandler method channelRead0.

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        LOGGER.debug("WebSocket Client connected!");
        handshakeFuture.setSuccess();
        return;
    }
    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new IllegalStateException("Unexpected FullHttpResponse (getStatus=" + response.status() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
    }
    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
        TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
        LOGGER.debug("WebSocket Client received text message: " + textFrame.text());
        String textReceived = textFrame.text();
        callback.call(textReceived);
    } else if (frame instanceof CloseWebSocketFrame) {
        isConnected = false;
        LOGGER.debug("WebSocket Client received closing");
        ch.close();
    }
}
Also used : CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) Channel(io.netty.channel.Channel) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) WebSocketFrame(io.netty.handler.codec.http.websocketx.WebSocketFrame) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame)

Example 30 with CloseWebSocketFrame

use of io.netty.handler.codec.http.websocketx.CloseWebSocketFrame in project netty-socketio by mrniko.

the class WebSocketTransport method channelRead.

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof CloseWebSocketFrame) {
        ctx.channel().writeAndFlush(msg).addListener(ChannelFutureListener.CLOSE);
    } else if (msg instanceof BinaryWebSocketFrame || msg instanceof TextWebSocketFrame) {
        ByteBufHolder frame = (ByteBufHolder) msg;
        ClientHead client = clientsBox.get(ctx.channel());
        if (client == null) {
            log.debug("Client with was already disconnected. Channel closed!");
            ctx.channel().close();
            frame.release();
            return;
        }
        ctx.pipeline().fireChannelRead(new PacketsMessage(client, frame.content(), Transport.WEBSOCKET));
        frame.release();
    } else if (msg instanceof FullHttpRequest) {
        FullHttpRequest req = (FullHttpRequest) msg;
        QueryStringDecoder queryDecoder = new QueryStringDecoder(req.uri());
        String path = queryDecoder.path();
        List<String> transport = queryDecoder.parameters().get("transport");
        List<String> sid = queryDecoder.parameters().get("sid");
        if (transport != null && NAME.equals(transport.get(0))) {
            try {
                if (!configuration.getTransports().contains(Transport.WEBSOCKET)) {
                    log.debug("{} transport not supported by configuration.", Transport.WEBSOCKET);
                    ctx.channel().close();
                    return;
                }
                if (sid != null && sid.get(0) != null) {
                    final UUID sessionId = UUID.fromString(sid.get(0));
                    handshake(ctx, sessionId, path, req);
                } else {
                    ClientHead client = ctx.channel().attr(ClientHead.CLIENT).get();
                    // first connection
                    handshake(ctx, client.getSessionId(), path, req);
                }
            } finally {
                req.release();
            }
        } else {
            ctx.fireChannelRead(msg);
        }
    } else {
        ctx.fireChannelRead(msg);
    }
}
Also used : CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) PacketsMessage(com.corundumstudio.socketio.messages.PacketsMessage) BinaryWebSocketFrame(io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame) ByteBufHolder(io.netty.buffer.ByteBufHolder) ClientHead(com.corundumstudio.socketio.handler.ClientHead) UUID(java.util.UUID)

Aggregations

CloseWebSocketFrame (io.netty.handler.codec.http.websocketx.CloseWebSocketFrame)41 PingWebSocketFrame (io.netty.handler.codec.http.websocketx.PingWebSocketFrame)23 TextWebSocketFrame (io.netty.handler.codec.http.websocketx.TextWebSocketFrame)23 PongWebSocketFrame (io.netty.handler.codec.http.websocketx.PongWebSocketFrame)22 WebSocketFrame (io.netty.handler.codec.http.websocketx.WebSocketFrame)17 URI (java.net.URI)13 CountDownLatch (java.util.concurrent.CountDownLatch)13 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)13 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)12 AtomicReference (java.util.concurrent.atomic.AtomicReference)12 WebSocketHandshakeException (io.netty.handler.codec.http.websocketx.WebSocketHandshakeException)11 Test (org.junit.jupiter.api.Test)11 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)10 HttpHeaderNames (io.netty.handler.codec.http.HttpHeaderNames)10 WebSocketClientHandshakeException (io.netty.handler.codec.http.websocketx.WebSocketClientHandshakeException)10 TimeUnit (java.util.concurrent.TimeUnit)10 Consumer (java.util.function.Consumer)10 Function (java.util.function.Function)10 Unpooled (io.netty.buffer.Unpooled)9 CorruptedFrameException (io.netty.handler.codec.CorruptedFrameException)9