Search in sources :

Example 1 with PingWebSocketFrame

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

the class HttpClientWSOperations method onInboundNext.

@Override
@SuppressWarnings("unchecked")
public void onInboundNext(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof FullHttpResponse) {
        started = true;
        channel().pipeline().remove(HttpObjectAggregator.class);
        FullHttpResponse response = (FullHttpResponse) msg;
        setNettyResponse(response);
        if (checkResponseCode(response)) {
            try {
                if (!handshaker.isHandshakeComplete()) {
                    handshaker.finishHandshake(channel(), response);
                }
            } catch (WebSocketHandshakeException wshe) {
                if (serverError) {
                    onInboundError(wshe);
                    return;
                }
            } finally {
                // Release unused content (101 status)
                response.content().release();
            }
            parentContext().fireContextActive(this);
            handshakerResult.trySuccess();
        }
        return;
    }
    if (msg instanceof PingWebSocketFrame) {
        channel().writeAndFlush(new PongWebSocketFrame(((PingWebSocketFrame) msg).content()));
        ctx.read();
        return;
    }
    if (msg instanceof CloseWebSocketFrame && ((CloseWebSocketFrame) msg).isFinalFragment()) {
        if (log.isDebugEnabled()) {
            log.debug("CloseWebSocketFrame detected. Closing Websocket");
        }
        CloseWebSocketFrame close = (CloseWebSocketFrame) msg;
        sendClose(new CloseWebSocketFrame(true, close.rsv(), close.content()));
    } else {
        super.onInboundNext(ctx, msg);
    }
}
Also used : CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) PongWebSocketFrame(io.netty.handler.codec.http.websocketx.PongWebSocketFrame) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) WebSocketHandshakeException(io.netty.handler.codec.http.websocketx.WebSocketHandshakeException) PingWebSocketFrame(io.netty.handler.codec.http.websocketx.PingWebSocketFrame)

Example 2 with PingWebSocketFrame

use of io.netty.handler.codec.http.websocketx.PingWebSocketFrame 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.info("WebSocket Client connected!");
        handshakeFuture.setSuccess();
        isOpen = true;
        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;
        textReceived = textFrame.text();
    } else if (frame instanceof BinaryWebSocketFrame) {
        BinaryWebSocketFrame binaryFrame = (BinaryWebSocketFrame) frame;
        bufferReceived = binaryFrame.content().nioBuffer();
    } else if (frame instanceof PingWebSocketFrame) {
        PingWebSocketFrame pingFrame = (PingWebSocketFrame) frame;
        isPing = true;
        bufferReceived = pingFrame.content().nioBuffer();
    } else if (frame instanceof PongWebSocketFrame) {
        PongWebSocketFrame pongFrame = (PongWebSocketFrame) frame;
        isPong = true;
        bufferReceived = pongFrame.content().nioBuffer();
    } else if (frame instanceof CloseWebSocketFrame) {
        ch.close().sync();
        isOpen = false;
    }
}
Also used : CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) PongWebSocketFrame(io.netty.handler.codec.http.websocketx.PongWebSocketFrame) Channel(io.netty.channel.Channel) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) BinaryWebSocketFrame(io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) WebSocketFrame(io.netty.handler.codec.http.websocketx.WebSocketFrame) PingWebSocketFrame(io.netty.handler.codec.http.websocketx.PingWebSocketFrame) BinaryWebSocketFrame(io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) PongWebSocketFrame(io.netty.handler.codec.http.websocketx.PongWebSocketFrame) CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) PingWebSocketFrame(io.netty.handler.codec.http.websocketx.PingWebSocketFrame)

Example 3 with PingWebSocketFrame

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

the class VMDebugServerHandler method handleWebSocketFrame.

private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
    // Check for closing frame
    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        return;
    }
    if (frame instanceof PingWebSocketFrame) {
        ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
        return;
    }
    if (!(frame instanceof TextWebSocketFrame)) {
        throw new DebugException(String.format("%s frame types not supported", frame.getClass().getName()));
    }
    String request = ((TextWebSocketFrame) frame).text();
    debugManager.processDebugCommand(request);
}
Also used : CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) PongWebSocketFrame(io.netty.handler.codec.http.websocketx.PongWebSocketFrame) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) PingWebSocketFrame(io.netty.handler.codec.http.websocketx.PingWebSocketFrame)

Example 4 with PingWebSocketFrame

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

the class WebSocketClient method main.

public static void main(String[] args) throws Exception {
    URI uri = new URI(URL);
    String scheme = uri.getScheme() == null ? "ws" : uri.getScheme();
    final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    final int port;
    if (uri.getPort() == -1) {
        if ("ws".equalsIgnoreCase(scheme)) {
            port = 80;
        } else if ("wss".equalsIgnoreCase(scheme)) {
            port = 443;
        } else {
            port = -1;
        }
    } else {
        port = uri.getPort();
    }
    if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) {
        System.err.println("Only WS(S) is supported.");
        return;
    }
    final boolean ssl = "wss".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00.
        // If you change it to V00, ping is not supported and remember to change
        // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
        final WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders()));
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) {
                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), host, port));
                }
                p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), WebSocketClientCompressionHandler.INSTANCE, handler);
            }
        });
        Channel ch = b.connect(uri.getHost(), port).sync().channel();
        handler.handshakeFuture().sync();
        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String msg = console.readLine();
            if (msg == null) {
                break;
            } else if ("bye".equals(msg.toLowerCase())) {
                ch.writeAndFlush(new CloseWebSocketFrame());
                ch.closeFuture().sync();
                break;
            } else if ("ping".equals(msg.toLowerCase())) {
                WebSocketFrame frame = new PingWebSocketFrame(Unpooled.wrappedBuffer(new byte[] { 8, 1, 8, 1 }));
                ch.writeAndFlush(frame);
            } else {
                WebSocketFrame frame = new TextWebSocketFrame(msg);
                ch.writeAndFlush(frame);
            }
        }
    } finally {
        group.shutdownGracefully();
    }
}
Also used : CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) InputStreamReader(java.io.InputStreamReader) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) PingWebSocketFrame(io.netty.handler.codec.http.websocketx.PingWebSocketFrame) URI(java.net.URI) ChannelPipeline(io.netty.channel.ChannelPipeline) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) BufferedReader(java.io.BufferedReader) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) Bootstrap(io.netty.bootstrap.Bootstrap) 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) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext)

Example 5 with PingWebSocketFrame

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

the class JsrWebSocketServer07Test method testPingPong.

@org.junit.Test
public void testPingPong() throws Exception {
    final byte[] payload = "payload".getBytes();
    final AtomicReference<Throwable> cause = new AtomicReference<>();
    final AtomicBoolean connected = new AtomicBoolean(false);
    final FutureResult<?> latch = new FutureResult<>();
    class TestEndPoint extends Endpoint {

        @Override
        public void onOpen(final Session session, EndpointConfig config) {
            connected.set(true);
        }
    }
    ServerWebSocketContainer builder = new ServerWebSocketContainer(TestClassIntrospector.INSTANCE, DefaultServer.getWorkerSupplier(), DefaultServer.getBufferPool(), Collections.emptyList(), false, false);
    builder.addEndpoint(ServerEndpointConfig.Builder.create(TestEndPoint.class, "/").configurator(new InstanceConfigurator(new TestEndPoint())).build());
    deployServlet(builder);
    WebSocketTestClient client = new WebSocketTestClient(getVersion(), new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/"));
    client.connect();
    client.send(new PingWebSocketFrame(Unpooled.wrappedBuffer(payload)), new FrameChecker(PongWebSocketFrame.class, payload, latch));
    // FIXME UNDERTOW-1862 assertEquals(DONE, latch.getIoFuture().await());
    latch.getIoFuture().await();
    assertNull(cause.get());
    client.destroy();
}
Also used : ServerWebSocketContainer(io.undertow.websockets.jsr.ServerWebSocketContainer) AtomicReference(java.util.concurrent.atomic.AtomicReference) PingWebSocketFrame(io.netty.handler.codec.http.websocketx.PingWebSocketFrame) URI(java.net.URI) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) WebSocketTestClient(io.undertow.websockets.utils.WebSocketTestClient) PongWebSocketFrame(io.netty.handler.codec.http.websocketx.PongWebSocketFrame) FutureResult(org.xnio.FutureResult) Endpoint(javax.websocket.Endpoint) AnnotatedClientEndpoint(io.undertow.websockets.jsr.test.annotated.AnnotatedClientEndpoint) FrameChecker(io.undertow.websockets.utils.FrameChecker) ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) EndpointConfig(javax.websocket.EndpointConfig) Session(javax.websocket.Session) UndertowSession(io.undertow.websockets.jsr.UndertowSession)

Aggregations

PingWebSocketFrame (io.netty.handler.codec.http.websocketx.PingWebSocketFrame)15 CloseWebSocketFrame (io.netty.handler.codec.http.websocketx.CloseWebSocketFrame)12 PongWebSocketFrame (io.netty.handler.codec.http.websocketx.PongWebSocketFrame)11 TextWebSocketFrame (io.netty.handler.codec.http.websocketx.TextWebSocketFrame)10 BinaryWebSocketFrame (io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame)6 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)4 Channel (io.netty.channel.Channel)3 ContinuationWebSocketFrame (io.netty.handler.codec.http.websocketx.ContinuationWebSocketFrame)3 WebSocketFrame (io.netty.handler.codec.http.websocketx.WebSocketFrame)3 URI (java.net.URI)3 FrameChecker (io.undertow.websockets.utils.FrameChecker)2 WebSocketTestClient (io.undertow.websockets.utils.WebSocketTestClient)2 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 Test (org.junit.jupiter.api.Test)2 FutureResult (org.xnio.FutureResult)2 ISerializer (io.crossbar.autobahn.wamp.interfaces.ISerializer)1 CloseDetails (io.crossbar.autobahn.wamp.types.CloseDetails)1 Bootstrap (io.netty.bootstrap.Bootstrap)1 ByteBuf (io.netty.buffer.ByteBuf)1 ChannelPipeline (io.netty.channel.ChannelPipeline)1