Search in sources :

Example 11 with WebSocketFrame

use of io.netty.handler.codec.http.websocketx.WebSocketFrame in project alien4cloud by alien4cloud.

the class WebSocketClientHandler method messageReceived.

@Override
public void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
    // The first message must be authentication response
    if (this.authenticationUrl != null && (this.cookies == null || this.cookies.isEmpty())) {
        HttpResponse response = (HttpResponse) msg;
        CharSequence cookieData = response.headers().get(new AsciiString("set-cookie"));
        if (cookieData != null) {
            this.cookies = ServerCookieDecoder.decode(cookieData.toString());
            if (this.cookies == null || this.cookies.isEmpty()) {
                throw new WebSocketAuthenticationFailureException("Could not authenticate");
            }
            if (log.isDebugEnabled()) {
                for (Cookie cookie : this.cookies) {
                    log.debug("Server says must set cookie with name {} and value {}", cookie.name(), cookie.value());
                }
            }
        } else {
            throw new ITException("Could not authenticate");
        }
        if (log.isDebugEnabled()) {
            log.debug("Authentication succeeded for user {}", this.user);
        }
        handShaker.handshake(ctx.channel());
        return;
    }
    // The second one must be the response for web socket handshake
    if (!handShaker.isHandshakeComplete()) {
        handShaker.finishHandshake(ctx.channel(), (FullHttpResponse) msg);
        if (log.isDebugEnabled()) {
            log.debug("Web socket client connected for user {}", this.user);
        }
        handshakeFuture.setSuccess();
        return;
    }
    // Take the byte buff and send it up to Stomp decoder
    if (msg instanceof WebSocketFrame) {
        if (log.isDebugEnabled()) {
            if (msg instanceof TextWebSocketFrame) {
                log.debug("Received text frame {}", ((TextWebSocketFrame) msg).text());
            }
        }
        ReferenceCountUtil.retain(msg);
        ctx.fireChannelRead(((WebSocketFrame) msg).content());
    }
}
Also used : ITException(alien4cloud.it.exception.ITException) AsciiString(io.netty.handler.codec.AsciiString) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) WebSocketFrame(io.netty.handler.codec.http.websocketx.WebSocketFrame) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame)

Example 12 with WebSocketFrame

use of io.netty.handler.codec.http.websocketx.WebSocketFrame in project alien4cloud by alien4cloud.

the class WebSocketClientHandler method write.

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (msg instanceof HttpRequest) {
        if (this.cookies != null && !this.cookies.isEmpty()) {
            HttpRequest request = (HttpRequest) msg;
            request.headers().set(new AsciiString("cookie"), ClientCookieEncoder.encode(cookies));
            if (log.isDebugEnabled()) {
                log.debug("Write HttpRequest {} enriched with security cookie", request);
            }
        }
        super.write(ctx, msg, promise);
        return;
    }
    String wrappedFrame = ((ByteBuf) msg).toString(Charset.forName("UTF-8"));
    if (log.isDebugEnabled()) {
        log.debug("Write text frame {}", wrappedFrame);
    }
    WebSocketFrame webSocketFrame = new TextWebSocketFrame(wrappedFrame);
    super.write(ctx, webSocketFrame, promise);
}
Also used : AsciiString(io.netty.handler.codec.AsciiString) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) WebSocketFrame(io.netty.handler.codec.http.websocketx.WebSocketFrame) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) AsciiString(io.netty.handler.codec.AsciiString) ByteBuf(io.netty.buffer.ByteBuf)

Example 13 with WebSocketFrame

use of io.netty.handler.codec.http.websocketx.WebSocketFrame in project undertow by undertow-io.

the class WebSocketTestClient method destroy.

/**
 * Destroy the client and also close open connections if any exist
 */
public void destroy() {
    if (!closed) {
        final CountDownLatch latch = new CountDownLatch(1);
        send(new CloseWebSocketFrame(), new FrameListener() {

            @Override
            public void onFrame(WebSocketFrame frame) {
                latch.countDown();
            }

            @Override
            public void onError(Throwable t) {
                latch.countDown();
            }
        });
        try {
            latch.await(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    // bootstrap.releaseExternalResources();
    if (ch != null) {
        ch.close().syncUninterruptibly();
    }
    try {
        bootstrap.group().shutdownGracefully(0, 1, TimeUnit.SECONDS).get();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } catch (ExecutionException e) {
        throw new RuntimeException(e);
    }
}
Also used : CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) WebSocketFrame(io.netty.handler.codec.http.websocketx.WebSocketFrame) CountDownLatch(java.util.concurrent.CountDownLatch) ExecutionException(java.util.concurrent.ExecutionException)

Example 14 with WebSocketFrame

use of io.netty.handler.codec.http.websocketx.WebSocketFrame 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 15 with WebSocketFrame

use of io.netty.handler.codec.http.websocketx.WebSocketFrame in project async-http-client by AsyncHttpClient.

the class WebSocketHandler method handleRead.

@Override
public void handleRead(Channel channel, NettyResponseFuture<?> future, Object e) throws Exception {
    if (e instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) e;
        if (logger.isDebugEnabled()) {
            HttpRequest httpRequest = future.getNettyRequest().getHttpRequest();
            logger.debug("\n\nRequest {}\n\nResponse {}\n", httpRequest, response);
        }
        WebSocketUpgradeHandler handler = getWebSocketUpgradeHandler(future);
        HttpResponseStatus status = new NettyResponseStatus(future.getUri(), response, channel);
        HttpHeaders responseHeaders = response.headers();
        if (!interceptors.exitAfterIntercept(channel, future, handler, response, status, responseHeaders)) {
            switch(handler.onStatusReceived(status)) {
                case CONTINUE:
                    upgrade(channel, future, handler, response, responseHeaders);
                    break;
                default:
                    abort(channel, future, handler, status);
            }
        }
    } else if (e instanceof WebSocketFrame) {
        WebSocketFrame frame = (WebSocketFrame) e;
        NettyWebSocket webSocket = getNettyWebSocket(future);
        // retain because we might buffer the frame
        if (webSocket.isReady()) {
            webSocket.handleFrame(frame);
        } else {
            // WebSocket hasn't been opened yet, but upgrading the pipeline triggered a read and a frame was sent along the HTTP upgrade response
            // as we want to keep sequential order (but can't notify user of open before upgrading so he doesn't to try send immediately), we have to buffer
            webSocket.bufferFrame(frame);
        }
    } else if (!(e instanceof LastHttpContent)) {
        // ignore, end of handshake response
        logger.error("Invalid message {}", e);
    }
}
Also used : NettyResponseStatus(org.asynchttpclient.netty.NettyResponseStatus) HttpResponseStatus(org.asynchttpclient.HttpResponseStatus) NettyWebSocket(org.asynchttpclient.netty.ws.NettyWebSocket) WebSocketFrame(io.netty.handler.codec.http.websocketx.WebSocketFrame) WebSocketUpgradeHandler(org.asynchttpclient.ws.WebSocketUpgradeHandler)

Aggregations

WebSocketFrame (io.netty.handler.codec.http.websocketx.WebSocketFrame)25 TextWebSocketFrame (io.netty.handler.codec.http.websocketx.TextWebSocketFrame)21 CloseWebSocketFrame (io.netty.handler.codec.http.websocketx.CloseWebSocketFrame)12 BinaryWebSocketFrame (io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame)11 ByteBuf (io.netty.buffer.ByteBuf)9 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)9 Test (org.junit.jupiter.api.Test)9 ContinuationWebSocketFrame (io.netty.handler.codec.http.websocketx.ContinuationWebSocketFrame)8 PingWebSocketFrame (io.netty.handler.codec.http.websocketx.PingWebSocketFrame)6 PongWebSocketFrame (io.netty.handler.codec.http.websocketx.PongWebSocketFrame)6 Channel (io.netty.channel.Channel)4 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)4 WebSocketHandshakeException (io.netty.handler.codec.http.websocketx.WebSocketHandshakeException)4 URI (java.net.URI)4 Unpooled (io.netty.buffer.Unpooled)3 CorruptedFrameException (io.netty.handler.codec.CorruptedFrameException)3 HttpHeaderNames (io.netty.handler.codec.http.HttpHeaderNames)3 HttpResponseStatus (io.netty.handler.codec.http.HttpResponseStatus)3 ClientCookieDecoder (io.netty.handler.codec.http.cookie.ClientCookieDecoder)3 ClientCookieEncoder (io.netty.handler.codec.http.cookie.ClientCookieEncoder)3