Search in sources :

Example 1 with WebSocketFrame

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

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

the class PerMessageDeflateDecoderTest method testIllegalStateWhenDecompressionInProgress.

@Test
public void testIllegalStateWhenDecompressionInProgress() {
    WebSocketExtensionFilter selectivityDecompressionFilter = new WebSocketExtensionFilter() {

        @Override
        public boolean mustSkip(WebSocketFrame frame) {
            return frame.content().readableBytes() < 100;
        }
    };
    EmbeddedChannel encoderChannel = new EmbeddedChannel(ZlibCodecFactory.newZlibEncoder(ZlibWrapper.NONE, 9, 15, 8));
    final EmbeddedChannel decoderChannel = new EmbeddedChannel(new PerMessageDeflateDecoder(false, selectivityDecompressionFilter));
    byte[] firstPayload = new byte[200];
    random.nextBytes(firstPayload);
    byte[] finalPayload = new byte[50];
    random.nextBytes(finalPayload);
    assertTrue(encoderChannel.writeOutbound(Unpooled.wrappedBuffer(firstPayload)));
    assertTrue(encoderChannel.writeOutbound(Unpooled.wrappedBuffer(finalPayload)));
    ByteBuf compressedFirstPayload = encoderChannel.readOutbound();
    ByteBuf compressedFinalPayload = encoderChannel.readOutbound();
    assertTrue(encoderChannel.finishAndReleaseAll());
    BinaryWebSocketFrame firstPart = new BinaryWebSocketFrame(false, WebSocketExtension.RSV1, compressedFirstPayload);
    final ContinuationWebSocketFrame finalPart = new ContinuationWebSocketFrame(true, WebSocketExtension.RSV1, compressedFinalPayload);
    assertTrue(decoderChannel.writeInbound(firstPart));
    BinaryWebSocketFrame outboundFirstPart = decoderChannel.readInbound();
    // first part is decompressed
    assertEquals(0, outboundFirstPart.rsv());
    assertArrayEquals(firstPayload, ByteBufUtil.getBytes(outboundFirstPart.content()));
    assertTrue(outboundFirstPart.release());
    // final part throwing exception
    try {
        assertThrows(DecoderException.class, new Executable() {

            @Override
            public void execute() {
                decoderChannel.writeInbound(finalPart);
            }
        });
    } finally {
        assertTrue(finalPart.release());
        assertFalse(encoderChannel.finishAndReleaseAll());
    }
}
Also used : ContinuationWebSocketFrame(io.netty.handler.codec.http.websocketx.ContinuationWebSocketFrame) WebSocketExtensionFilter(io.netty.handler.codec.http.websocketx.extensions.WebSocketExtensionFilter) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) BinaryWebSocketFrame(io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame) WebSocketFrame(io.netty.handler.codec.http.websocketx.WebSocketFrame) ContinuationWebSocketFrame(io.netty.handler.codec.http.websocketx.ContinuationWebSocketFrame) BinaryWebSocketFrame(io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) ByteBuf(io.netty.buffer.ByteBuf) Executable(org.junit.jupiter.api.function.Executable) Test(org.junit.jupiter.api.Test)

Example 3 with WebSocketFrame

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

the class PerMessageDeflateEncoderTest method testIllegalStateWhenCompressionInProgress.

@Test
public void testIllegalStateWhenCompressionInProgress() {
    WebSocketExtensionFilter selectivityCompressionFilter = new WebSocketExtensionFilter() {

        @Override
        public boolean mustSkip(WebSocketFrame frame) {
            return frame.content().readableBytes() < 100;
        }
    };
    final EmbeddedChannel encoderChannel = new EmbeddedChannel(new PerMessageDeflateEncoder(9, 15, false, selectivityCompressionFilter));
    byte[] firstPayload = new byte[200];
    random.nextBytes(firstPayload);
    byte[] finalPayload = new byte[90];
    random.nextBytes(finalPayload);
    BinaryWebSocketFrame firstPart = new BinaryWebSocketFrame(false, 0, Unpooled.wrappedBuffer(firstPayload));
    final ContinuationWebSocketFrame finalPart = new ContinuationWebSocketFrame(true, 0, Unpooled.wrappedBuffer(finalPayload));
    assertTrue(encoderChannel.writeOutbound(firstPart));
    BinaryWebSocketFrame outboundFirstPart = encoderChannel.readOutbound();
    // first part is compressed
    assertEquals(WebSocketExtension.RSV1, outboundFirstPart.rsv());
    assertFalse(Arrays.equals(firstPayload, ByteBufUtil.getBytes(outboundFirstPart.content())));
    assertTrue(outboundFirstPart.release());
    // final part throwing exception
    try {
        assertThrows(EncoderException.class, new Executable() {

            @Override
            public void execute() throws Throwable {
                encoderChannel.writeOutbound(finalPart);
            }
        });
    } finally {
        assertTrue(finalPart.release());
        assertFalse(encoderChannel.finishAndReleaseAll());
    }
}
Also used : ContinuationWebSocketFrame(io.netty.handler.codec.http.websocketx.ContinuationWebSocketFrame) WebSocketExtensionFilter(io.netty.handler.codec.http.websocketx.extensions.WebSocketExtensionFilter) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) BinaryWebSocketFrame(io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame) WebSocketFrame(io.netty.handler.codec.http.websocketx.WebSocketFrame) ContinuationWebSocketFrame(io.netty.handler.codec.http.websocketx.ContinuationWebSocketFrame) BinaryWebSocketFrame(io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) Executable(org.junit.jupiter.api.function.Executable) Test(org.junit.jupiter.api.Test)

Example 4 with WebSocketFrame

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

the class PerMessageDeflateEncoderTest method testSelectivityCompressionSkip.

@Test
public void testSelectivityCompressionSkip() {
    WebSocketExtensionFilter selectivityCompressionFilter = new WebSocketExtensionFilter() {

        @Override
        public boolean mustSkip(WebSocketFrame frame) {
            return (frame instanceof TextWebSocketFrame || frame instanceof BinaryWebSocketFrame) && frame.content().readableBytes() < 100;
        }
    };
    EmbeddedChannel encoderChannel = new EmbeddedChannel(new PerMessageDeflateEncoder(9, 15, false, selectivityCompressionFilter));
    EmbeddedChannel decoderChannel = new EmbeddedChannel(ZlibCodecFactory.newZlibDecoder(ZlibWrapper.NONE));
    String textPayload = "not compressed payload";
    byte[] binaryPayload = new byte[101];
    random.nextBytes(binaryPayload);
    WebSocketFrame textFrame = new TextWebSocketFrame(textPayload);
    BinaryWebSocketFrame binaryFrame = new BinaryWebSocketFrame(Unpooled.wrappedBuffer(binaryPayload));
    assertTrue(encoderChannel.writeOutbound(textFrame));
    assertTrue(encoderChannel.writeOutbound(binaryFrame));
    WebSocketFrame outboundTextFrame = encoderChannel.readOutbound();
    // compression skipped for textFrame
    assertEquals(0, outboundTextFrame.rsv());
    assertEquals(textPayload, outboundTextFrame.content().toString(UTF_8));
    assertTrue(outboundTextFrame.release());
    WebSocketFrame outboundBinaryFrame = encoderChannel.readOutbound();
    // compression not skipped for binaryFrame
    assertEquals(WebSocketExtension.RSV1, outboundBinaryFrame.rsv());
    assertTrue(decoderChannel.writeInbound(outboundBinaryFrame.content().retain()));
    ByteBuf uncompressedBinaryPayload = decoderChannel.readInbound();
    assertArrayEquals(binaryPayload, ByteBufUtil.getBytes(uncompressedBinaryPayload));
    assertTrue(outboundBinaryFrame.release());
    assertTrue(uncompressedBinaryPayload.release());
    assertFalse(encoderChannel.finish());
    assertFalse(decoderChannel.finish());
}
Also used : TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) WebSocketExtensionFilter(io.netty.handler.codec.http.websocketx.extensions.WebSocketExtensionFilter) BinaryWebSocketFrame(io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) WebSocketFrame(io.netty.handler.codec.http.websocketx.WebSocketFrame) ContinuationWebSocketFrame(io.netty.handler.codec.http.websocketx.ContinuationWebSocketFrame) BinaryWebSocketFrame(io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) ByteBuf(io.netty.buffer.ByteBuf) Test(org.junit.jupiter.api.Test)

Example 5 with WebSocketFrame

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

Aggregations

WebSocketFrame (io.netty.handler.codec.http.websocketx.WebSocketFrame)19 TextWebSocketFrame (io.netty.handler.codec.http.websocketx.TextWebSocketFrame)16 BinaryWebSocketFrame (io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame)11 ByteBuf (io.netty.buffer.ByteBuf)8 ContinuationWebSocketFrame (io.netty.handler.codec.http.websocketx.ContinuationWebSocketFrame)8 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)6 CloseWebSocketFrame (io.netty.handler.codec.http.websocketx.CloseWebSocketFrame)6 Test (org.junit.jupiter.api.Test)6 Channel (io.netty.channel.Channel)4 WebSocketExtensionFilter (io.netty.handler.codec.http.websocketx.extensions.WebSocketExtensionFilter)4 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)3 CompositeByteBuf (io.netty.buffer.CompositeByteBuf)2 AsciiString (io.netty.handler.codec.AsciiString)2 CodecException (io.netty.handler.codec.CodecException)2 PingWebSocketFrame (io.netty.handler.codec.http.websocketx.PingWebSocketFrame)2 PongWebSocketFrame (io.netty.handler.codec.http.websocketx.PongWebSocketFrame)2 ExecutionException (java.util.concurrent.ExecutionException)2 Executable (org.junit.jupiter.api.function.Executable)2 ITException (alien4cloud.it.exception.ITException)1 Packet (com.corundumstudio.socketio.protocol.Packet)1