Search in sources :

Example 11 with PingWebSocketFrame

use of io.netty.handler.codec.http.websocketx.PingWebSocketFrame in project reactor-netty by reactor.

the class HttpServerWSOperations method onInboundNext.

@Override
public void onInboundNext(ChannelHandlerContext ctx, Object frame) {
    if (frame instanceof CloseWebSocketFrame && ((CloseWebSocketFrame) frame).isFinalFragment()) {
        if (log.isDebugEnabled()) {
            log.debug("CloseWebSocketFrame detected. Closing Websocket");
        }
        CloseWebSocketFrame close = (CloseWebSocketFrame) frame;
        sendClose(new CloseWebSocketFrame(true, close.rsv(), close.content()), f -> onHandlerTerminate());
        return;
    }
    if (frame instanceof PingWebSocketFrame) {
        ctx.writeAndFlush(new PongWebSocketFrame(((PingWebSocketFrame) frame).content()));
        ctx.read();
        return;
    }
    super.onInboundNext(ctx, frame);
}
Also used : CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) PongWebSocketFrame(io.netty.handler.codec.http.websocketx.PongWebSocketFrame) PingWebSocketFrame(io.netty.handler.codec.http.websocketx.PingWebSocketFrame)

Example 12 with PingWebSocketFrame

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

the class WebSocket07ServerTest method testPing.

@Test
public void testPing() throws Exception {
    final AtomicBoolean connected = new AtomicBoolean(false);
    DefaultServer.setRootHandler(new WebSocketProtocolHandshakeHandler(new WebSocketConnectionCallback() {

        @Override
        public void onConnect(final WebSocketHttpExchange exchange, final WebSocketChannel channel) {
            connected.set(true);
            channel.getReceiveSetter().set(new AbstractReceiveListener() {

                @Override
                protected void onFullPingMessage(WebSocketChannel channel, BufferedBinaryMessage message) throws IOException {
                    final Pooled<ByteBuffer[]> data = message.getData();
                    WebSockets.sendPong(data.getResource(), channel, new WebSocketCallback<Void>() {

                        @Override
                        public void complete(WebSocketChannel channel, Void context) {
                            data.close();
                        }

                        @Override
                        public void onError(WebSocketChannel channel, Void context, Throwable throwable) {
                            data.close();
                        }
                    });
                }
            });
            channel.resumeReceives();
        }
    }));
    final FutureResult latch = new FutureResult();
    final byte[] payload = "payload".getBytes();
    WebSocketTestClient client = new WebSocketTestClient(getVersion(), new URI("ws://" + NetworkUtils.formatPossibleIpv6Address(DefaultServer.getHostAddress("default")) + ':' + DefaultServer.getHostPort("default") + '/'));
    client.connect();
    client.send(new PingWebSocketFrame(Unpooled.wrappedBuffer(payload)), new FrameChecker(PongWebSocketFrame.class, payload, latch));
    latch.getIoFuture().get();
    client.destroy();
}
Also used : WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) Pooled(org.xnio.Pooled) IOException(java.io.IOException) PingWebSocketFrame(io.netty.handler.codec.http.websocketx.PingWebSocketFrame) ByteBuffer(java.nio.ByteBuffer) URI(java.net.URI) WebSocketHttpExchange(io.undertow.websockets.spi.WebSocketHttpExchange) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) WebSocketTestClient(io.undertow.websockets.utils.WebSocketTestClient) PongWebSocketFrame(io.netty.handler.codec.http.websocketx.PongWebSocketFrame) FutureResult(org.xnio.FutureResult) WebSocketCallback(io.undertow.websockets.core.WebSocketCallback) AbstractReceiveListener(io.undertow.websockets.core.AbstractReceiveListener) FrameChecker(io.undertow.websockets.utils.FrameChecker) WebSocketProtocolHandshakeHandler(io.undertow.websockets.WebSocketProtocolHandshakeHandler) BufferedBinaryMessage(io.undertow.websockets.core.BufferedBinaryMessage) WebSocketConnectionCallback(io.undertow.websockets.WebSocketConnectionCallback) Test(org.junit.Test)

Example 13 with PingWebSocketFrame

use of io.netty.handler.codec.http.websocketx.PingWebSocketFrame in project vert.x by eclipse.

the class Http1xConnectionBase method decodeFrame.

private WebSocketFrameInternal decodeFrame(io.netty.handler.codec.http.websocketx.WebSocketFrame msg) {
    ByteBuf payload = safeBuffer(msg.content());
    boolean isFinal = msg.isFinalFragment();
    WebSocketFrameType frameType;
    if (msg instanceof BinaryWebSocketFrame) {
        frameType = WebSocketFrameType.BINARY;
    } else if (msg instanceof CloseWebSocketFrame) {
        frameType = WebSocketFrameType.CLOSE;
    } else if (msg instanceof PingWebSocketFrame) {
        frameType = WebSocketFrameType.PING;
    } else if (msg instanceof PongWebSocketFrame) {
        frameType = WebSocketFrameType.PONG;
    } else if (msg instanceof TextWebSocketFrame) {
        frameType = WebSocketFrameType.TEXT;
    } else if (msg instanceof ContinuationWebSocketFrame) {
        frameType = WebSocketFrameType.CONTINUATION;
    } else {
        throw new IllegalStateException("Unsupported WebSocket msg " + msg);
    }
    return new WebSocketFrameImpl(frameType, payload, isFinal);
}
Also used : CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) PongWebSocketFrame(io.netty.handler.codec.http.websocketx.PongWebSocketFrame) WebSocketFrameImpl(io.vertx.core.http.impl.ws.WebSocketFrameImpl) ContinuationWebSocketFrame(io.netty.handler.codec.http.websocketx.ContinuationWebSocketFrame) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) BinaryWebSocketFrame(io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame) WebSocketFrameType(io.vertx.core.http.WebSocketFrameType) ByteBuf(io.netty.buffer.ByteBuf) PingWebSocketFrame(io.netty.handler.codec.http.websocketx.PingWebSocketFrame)

Example 14 with PingWebSocketFrame

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

use of io.netty.handler.codec.http.websocketx.PingWebSocketFrame 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)

Aggregations

PingWebSocketFrame (io.netty.handler.codec.http.websocketx.PingWebSocketFrame)21 CloseWebSocketFrame (io.netty.handler.codec.http.websocketx.CloseWebSocketFrame)18 PongWebSocketFrame (io.netty.handler.codec.http.websocketx.PongWebSocketFrame)17 TextWebSocketFrame (io.netty.handler.codec.http.websocketx.TextWebSocketFrame)14 WebSocketFrame (io.netty.handler.codec.http.websocketx.WebSocketFrame)7 URI (java.net.URI)7 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)6 Test (org.junit.jupiter.api.Test)6 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)5 BinaryWebSocketFrame (io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame)5 WebSocketClientHandshakeException (io.netty.handler.codec.http.websocketx.WebSocketClientHandshakeException)5 WebSocketHandshakeException (io.netty.handler.codec.http.websocketx.WebSocketHandshakeException)5 AtomicReference (java.util.concurrent.atomic.AtomicReference)5 Unpooled (io.netty.buffer.Unpooled)4 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)4 CorruptedFrameException (io.netty.handler.codec.CorruptedFrameException)4 HttpHeaderNames (io.netty.handler.codec.http.HttpHeaderNames)4 HttpResponseStatus (io.netty.handler.codec.http.HttpResponseStatus)4 ClientCookieDecoder (io.netty.handler.codec.http.cookie.ClientCookieDecoder)4 ClientCookieEncoder (io.netty.handler.codec.http.cookie.ClientCookieEncoder)4