Search in sources :

Example 21 with BinaryWebSocketFrame

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

the class PerFrameDeflateEncoderTest method testCompressedFrame.

@Test
public void testCompressedFrame() {
    EmbeddedChannel encoderChannel = new EmbeddedChannel(new PerFrameDeflateEncoder(9, 15, false));
    EmbeddedChannel decoderChannel = new EmbeddedChannel(ZlibCodecFactory.newZlibDecoder(ZlibWrapper.NONE));
    // initialize
    byte[] payload = new byte[300];
    random.nextBytes(payload);
    BinaryWebSocketFrame frame = new BinaryWebSocketFrame(true, WebSocketExtension.RSV3, Unpooled.wrappedBuffer(payload));
    // execute
    encoderChannel.writeOutbound(frame);
    BinaryWebSocketFrame compressedFrame = encoderChannel.readOutbound();
    // test
    assertNotNull(compressedFrame);
    assertNotNull(compressedFrame.content());
    assertTrue(compressedFrame instanceof BinaryWebSocketFrame);
    assertEquals(WebSocketExtension.RSV1 | WebSocketExtension.RSV3, compressedFrame.rsv());
    decoderChannel.writeInbound(compressedFrame.content());
    decoderChannel.writeInbound(DeflateDecoder.FRAME_TAIL);
    ByteBuf uncompressedPayload = decoderChannel.readInbound();
    assertEquals(300, uncompressedPayload.readableBytes());
    byte[] finalPayload = new byte[300];
    uncompressedPayload.readBytes(finalPayload);
    assertTrue(Arrays.equals(finalPayload, payload));
    uncompressedPayload.release();
}
Also used : EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) BinaryWebSocketFrame(io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame) ByteBuf(io.netty.buffer.ByteBuf) Test(org.junit.Test)

Example 22 with BinaryWebSocketFrame

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

the class PerFrameDeflateEncoderTest method testFramementedFrame.

@Test
public void testFramementedFrame() {
    EmbeddedChannel encoderChannel = new EmbeddedChannel(new PerFrameDeflateEncoder(9, 15, false));
    EmbeddedChannel decoderChannel = new EmbeddedChannel(ZlibCodecFactory.newZlibDecoder(ZlibWrapper.NONE));
    // initialize
    byte[] payload1 = new byte[100];
    random.nextBytes(payload1);
    byte[] payload2 = new byte[100];
    random.nextBytes(payload2);
    byte[] payload3 = new byte[100];
    random.nextBytes(payload3);
    BinaryWebSocketFrame frame1 = new BinaryWebSocketFrame(false, WebSocketExtension.RSV3, Unpooled.wrappedBuffer(payload1));
    ContinuationWebSocketFrame frame2 = new ContinuationWebSocketFrame(false, WebSocketExtension.RSV3, Unpooled.wrappedBuffer(payload2));
    ContinuationWebSocketFrame frame3 = new ContinuationWebSocketFrame(true, WebSocketExtension.RSV3, Unpooled.wrappedBuffer(payload3));
    // execute
    encoderChannel.writeOutbound(frame1);
    encoderChannel.writeOutbound(frame2);
    encoderChannel.writeOutbound(frame3);
    BinaryWebSocketFrame compressedFrame1 = encoderChannel.readOutbound();
    ContinuationWebSocketFrame compressedFrame2 = encoderChannel.readOutbound();
    ContinuationWebSocketFrame compressedFrame3 = encoderChannel.readOutbound();
    // test
    assertNotNull(compressedFrame1);
    assertNotNull(compressedFrame2);
    assertNotNull(compressedFrame3);
    assertEquals(WebSocketExtension.RSV1 | WebSocketExtension.RSV3, compressedFrame1.rsv());
    assertEquals(WebSocketExtension.RSV1 | WebSocketExtension.RSV3, compressedFrame2.rsv());
    assertEquals(WebSocketExtension.RSV1 | WebSocketExtension.RSV3, compressedFrame3.rsv());
    assertFalse(compressedFrame1.isFinalFragment());
    assertFalse(compressedFrame2.isFinalFragment());
    assertTrue(compressedFrame3.isFinalFragment());
    decoderChannel.writeInbound(compressedFrame1.content());
    decoderChannel.writeInbound(Unpooled.wrappedBuffer(DeflateDecoder.FRAME_TAIL));
    ByteBuf uncompressedPayload1 = decoderChannel.readInbound();
    byte[] finalPayload1 = new byte[100];
    uncompressedPayload1.readBytes(finalPayload1);
    assertTrue(Arrays.equals(finalPayload1, payload1));
    uncompressedPayload1.release();
    decoderChannel.writeInbound(compressedFrame2.content());
    decoderChannel.writeInbound(Unpooled.wrappedBuffer(DeflateDecoder.FRAME_TAIL));
    ByteBuf uncompressedPayload2 = decoderChannel.readInbound();
    byte[] finalPayload2 = new byte[100];
    uncompressedPayload2.readBytes(finalPayload2);
    assertTrue(Arrays.equals(finalPayload2, payload2));
    uncompressedPayload2.release();
    decoderChannel.writeInbound(compressedFrame3.content());
    decoderChannel.writeInbound(Unpooled.wrappedBuffer(DeflateDecoder.FRAME_TAIL));
    ByteBuf uncompressedPayload3 = decoderChannel.readInbound();
    byte[] finalPayload3 = new byte[100];
    uncompressedPayload3.readBytes(finalPayload3);
    assertTrue(Arrays.equals(finalPayload3, payload3));
    uncompressedPayload3.release();
}
Also used : ContinuationWebSocketFrame(io.netty.handler.codec.http.websocketx.ContinuationWebSocketFrame) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) BinaryWebSocketFrame(io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame) ByteBuf(io.netty.buffer.ByteBuf) Test(org.junit.Test)

Example 23 with BinaryWebSocketFrame

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

the class EncoderHandler method handleWebsocket.

private void handleWebsocket(final OutPacketMessage msg, ChannelHandlerContext ctx, ChannelPromise promise) throws IOException {
    while (true) {
        Queue<Packet> queue = msg.getClientHead().getPacketsQueue(msg.getTransport());
        Packet packet = queue.poll();
        if (packet == null) {
            promise.trySuccess();
            break;
        }
        final ByteBuf out = encoder.allocateBuffer(ctx.alloc());
        encoder.encodePacket(packet, out, ctx.alloc(), true);
        WebSocketFrame res = new TextWebSocketFrame(out);
        if (log.isTraceEnabled()) {
            log.trace("Out message: {} sessionId: {}", out.toString(CharsetUtil.UTF_8), msg.getSessionId());
        }
        if (out.isReadable()) {
            if (!promise.isDone()) {
                ctx.channel().writeAndFlush(res, promise);
            } else {
                ctx.channel().writeAndFlush(res);
            }
        } else {
            promise.trySuccess();
            out.release();
        }
        for (ByteBuf buf : packet.getAttachments()) {
            ByteBuf outBuf = encoder.allocateBuffer(ctx.alloc());
            outBuf.writeByte(4);
            outBuf.writeBytes(buf);
            if (log.isTraceEnabled()) {
                log.trace("Out attachment: {} sessionId: {}", ByteBufUtil.hexDump(outBuf), msg.getSessionId());
            }
            ctx.channel().writeAndFlush(new BinaryWebSocketFrame(outBuf));
        }
    }
}
Also used : Packet(com.corundumstudio.socketio.protocol.Packet) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) BinaryWebSocketFrame(io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame) WebSocketFrame(io.netty.handler.codec.http.websocketx.WebSocketFrame) BinaryWebSocketFrame(io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) ByteBuf(io.netty.buffer.ByteBuf)

Example 24 with BinaryWebSocketFrame

use of io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame 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().close();
        ReferenceCountUtil.release(msg);
    } 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)

Example 25 with BinaryWebSocketFrame

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

the class JsrWebSocketServer07Test method testBinaryWithByteBufferByFuture.

@org.junit.Test
public void testBinaryWithByteBufferByFuture() throws Exception {
    final byte[] payload = "payload".getBytes();
    final AtomicReference<Future<Void>> sendResult = 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);
            session.addMessageHandler(new MessageHandler.Whole<ByteBuffer>() {

                @Override
                public void onMessage(ByteBuffer message) {
                    ByteBuffer buf = ByteBuffer.allocate(message.remaining());
                    buf.put(message);
                    buf.flip();
                    sendResult.set(session.getAsyncRemote().sendBinary(buf));
                }
            });
        }
    }
    ServerWebSocketContainer builder = new ServerWebSocketContainer(TestClassIntrospector.INSTANCE, DefaultServer.getWorker(), DefaultServer.getBufferPool(), Collections.EMPTY_LIST, 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 BinaryWebSocketFrame(Unpooled.wrappedBuffer(payload)), new FrameChecker(BinaryWebSocketFrame.class, payload, latch));
    latch.getIoFuture().get();
    Future<Void> result = sendResult.get();
    client.destroy();
}
Also used : MessageHandler(javax.websocket.MessageHandler) ServerWebSocketContainer(io.undertow.websockets.jsr.ServerWebSocketContainer) BinaryWebSocketFrame(io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame) AtomicReference(java.util.concurrent.atomic.AtomicReference) ByteBuffer(java.nio.ByteBuffer) URI(java.net.URI) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) WebSocketTestClient(io.undertow.websockets.utils.WebSocketTestClient) FutureResult(org.xnio.FutureResult) Endpoint(javax.websocket.Endpoint) AnnotatedClientEndpoint(io.undertow.websockets.jsr.test.annotated.AnnotatedClientEndpoint) FrameChecker(io.undertow.websockets.utils.FrameChecker) Future(java.util.concurrent.Future) IoFuture(org.xnio.IoFuture) ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) EndpointConfig(javax.websocket.EndpointConfig) Session(javax.websocket.Session) UndertowSession(io.undertow.websockets.jsr.UndertowSession) Test(org.junit.Test)

Aggregations

BinaryWebSocketFrame (io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame)28 Test (org.junit.Test)20 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)15 ByteBuf (io.netty.buffer.ByteBuf)12 FrameChecker (io.undertow.websockets.utils.FrameChecker)7 WebSocketTestClient (io.undertow.websockets.utils.WebSocketTestClient)7 URI (java.net.URI)7 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)7 FutureResult (org.xnio.FutureResult)7 ServerWebSocketContainer (io.undertow.websockets.jsr.ServerWebSocketContainer)6 UndertowSession (io.undertow.websockets.jsr.UndertowSession)6 AnnotatedClientEndpoint (io.undertow.websockets.jsr.test.annotated.AnnotatedClientEndpoint)6 AtomicReference (java.util.concurrent.atomic.AtomicReference)6 Endpoint (javax.websocket.Endpoint)6 EndpointConfig (javax.websocket.EndpointConfig)6 MessageHandler (javax.websocket.MessageHandler)6 Session (javax.websocket.Session)6 ServerEndpointConfig (javax.websocket.server.ServerEndpointConfig)6 ContinuationWebSocketFrame (io.netty.handler.codec.http.websocketx.ContinuationWebSocketFrame)5 TextWebSocketFrame (io.netty.handler.codec.http.websocketx.TextWebSocketFrame)5