Example usage for io.netty.handler.codec.http.websocketx TextWebSocketFrame TextWebSocketFrame

List of usage examples for io.netty.handler.codec.http.websocketx TextWebSocketFrame TextWebSocketFrame

Introduction

In this page you can find the example usage for io.netty.handler.codec.http.websocketx TextWebSocketFrame TextWebSocketFrame.

Prototype

public TextWebSocketFrame(boolean finalFragment, int rsv, ByteBuf binaryData) 

Source Link

Document

Creates a new text frame with the specified binary data and the final fragment flag.

Usage

From source file:io.advantageous.conekt.http.impl.ConektHttpHandler.java

License:Open Source License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (msg instanceof WebSocketFrameInternal) {
        WebSocketFrameInternal frame = (WebSocketFrameInternal) msg;
        ByteBuf buf = frame.getBinaryData();
        if (buf != Unpooled.EMPTY_BUFFER) {
            buf = safeBuffer(buf, ctx.alloc());
        }/*from   www . j a  v  a  2s  .  c  o m*/
        switch (frame.type()) {
        case BINARY:
            msg = new BinaryWebSocketFrame(frame.isFinal(), 0, buf);
            break;
        case TEXT:
            msg = new TextWebSocketFrame(frame.isFinal(), 0, buf);
            break;
        case CLOSE:
            msg = new CloseWebSocketFrame(true, 0, buf);
            break;
        case CONTINUATION:
            msg = new ContinuationWebSocketFrame(frame.isFinal(), 0, buf);
            break;
        case PONG:
            msg = new PongWebSocketFrame(buf);
            break;
        case PING:
            msg = new PingWebSocketFrame(buf);
            break;
        default:
            throw new IllegalStateException("Unsupported websocket msg " + msg);
        }
    }
    ctx.write(msg, promise);
}

From source file:io.reactivex.netty.protocol.http.websocket.WebSocketClientServerTest.java

License:Apache License

@Test
public void testFragmentedMessage() throws Exception {
    TestSequenceExecutor executor = new TestSequenceExecutor()
            .withClientFrames(new TextWebSocketFrame(false, 0, "first"),
                    new ContinuationWebSocketFrame(false, 0, "middle"),
                    new ContinuationWebSocketFrame(true, 0, "last"))
            .withExpectedOnServer(3).execute();

    assertEquals("Expected first frame content", "first", asText(executor.getReceivedClientFrames().get(0)));
    assertEquals("Expected first frame content", "middle", asText(executor.getReceivedClientFrames().get(1)));
    assertEquals("Expected first frame content", "last", asText(executor.getReceivedClientFrames().get(2)));
}

From source file:io.reactivex.netty.protocol.http.websocket.WebSocketClientServerTest.java

License:Apache License

@Test
public void testMessageAggregationOnServer() throws Exception {
    TestSequenceExecutor executor = new TestSequenceExecutor().withMessageAggregation(true)
            .withClientFrames(new TextWebSocketFrame(false, 0, "0123456789"),
                    new ContinuationWebSocketFrame(true, 0, "ABCDEFGHIJ"))
            .withExpectedOnServer(1).execute();
    assertEquals("Expected aggregated message", "0123456789ABCDEFGHIJ",
            asText(executor.getReceivedClientFrames().get(0)));
}

From source file:io.reactivex.netty.protocol.http.websocket.WebSocketClientServerTest.java

License:Apache License

@Test
public void testMessageAggregationOnClient() throws Exception {
    TestSequenceExecutor executor = new TestSequenceExecutor().withMessageAggregation(true)
            .withServerFrames(new TextWebSocketFrame(false, 0, "0123456789"),
                    new ContinuationWebSocketFrame(true, 0, "ABCDEFGHIJ"))
            .withExpectedOnClient(1).execute();
    assertEquals("Expected aggregated message", "0123456789ABCDEFGHIJ",
            asText(executor.getReceivedServerFrames().get(0)));
}

From source file:io.vertx.core.http.impl.Http1xConnectionBase.java

License:Open Source License

WebSocketFrame encodeFrame(WebSocketFrameImpl frame) {
    ByteBuf buf = frame.getBinaryData();
    if (buf != Unpooled.EMPTY_BUFFER) {
        buf = safeBuffer(buf, chctx.alloc());
    }//from w  w  w. j a va2  s  .co  m
    switch (frame.type()) {
    case BINARY:
        return new BinaryWebSocketFrame(frame.isFinal(), 0, buf);
    case TEXT:
        return new TextWebSocketFrame(frame.isFinal(), 0, buf);
    case CLOSE:
        return new CloseWebSocketFrame(true, 0, buf);
    case CONTINUATION:
        return new ContinuationWebSocketFrame(frame.isFinal(), 0, buf);
    case PONG:
        return new PongWebSocketFrame(buf);
    case PING:
        return new PingWebSocketFrame(buf);
    default:
        throw new IllegalStateException("Unsupported websocket msg " + frame);
    }
}

From source file:org.apache.tinkerpop.gremlin.server.handler.WsGremlinResponseEncoder.java

License:Apache License

@Override
protected void encode(final ChannelHandlerContext ctx, final ResponseMessage o, final List<Object> objects)
        throws Exception {
    final MessageSerializer serializer = ctx.channel().attr(StateKey.SERIALIZER).get();
    final boolean useBinary = ctx.channel().attr(StateKey.USE_BINARY).get();
    final Session session = ctx.channel().attr(StateKey.SESSION).get();

    try {/*www.  ja v a 2  s. co  m*/
        if (!o.getStatus().getCode().isSuccess())
            errorMeter.mark();

        if (useBinary) {
            final ByteBuf serialized;

            // if the request came in on a session then the serialization must occur in that same thread.
            if (null == session)
                serialized = serializer.serializeResponseAsBinary(o, ctx.alloc());
            else
                serialized = session.getExecutor()
                        .submit(() -> serializer.serializeResponseAsBinary(o, ctx.alloc())).get();

            objects.add(new BinaryWebSocketFrame(serialized));
        } else {
            // the expectation is that the GremlinTextRequestDecoder will have placed a MessageTextSerializer
            // instance on the channel.
            final MessageTextSerializer textSerializer = (MessageTextSerializer) serializer;

            final String serialized;

            // if the request came in on a session then the serialization must occur in that same thread.
            if (null == session)
                serialized = textSerializer.serializeResponseAsString(o);
            else
                serialized = session.getExecutor().submit(() -> textSerializer.serializeResponseAsString(o))
                        .get();

            objects.add(new TextWebSocketFrame(true, 0, serialized));
        }
    } catch (Exception ex) {
        errorMeter.mark();
        logger.warn("The result [{}] in the request {} could not be serialized and returned.", o.getResult(),
                o.getRequestId(), ex);
        final String errorMessage = String.format("Error during serialization: %s",
                ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage());
        final ResponseMessage error = ResponseMessage.build(o.getRequestId()).statusMessage(errorMessage)
                .code(ResponseStatusCode.SERVER_ERROR_SERIALIZATION).create();
        if (useBinary) {
            objects.add(new BinaryWebSocketFrame(serializer.serializeResponseAsBinary(error, ctx.alloc())));
        } else {
            final MessageTextSerializer textSerializer = (MessageTextSerializer) serializer;
            objects.add(new TextWebSocketFrame(textSerializer.serializeResponseAsString(error)));
        }
    }
}

From source file:org.apache.tinkerpop.gremlin.server.handler.WsGremlinResponseFrameEncoder.java

License:Apache License

@Override
protected void encode(final ChannelHandlerContext ctx, final Frame o, final List<Object> objects)
        throws Exception {
    if (o.getMsg() instanceof ByteBuf)
        objects.add(new BinaryWebSocketFrame((ByteBuf) o.getMsg()));
    else if (o.getMsg() instanceof String)
        objects.add(new TextWebSocketFrame(true, 0, o.getMsg().toString()));
}

From source file:org.asynchttpclient.netty.ws.NettyWebSocket.java

License:Open Source License

@Override
public WebSocket stream(String fragment, boolean last) {
    channel.writeAndFlush(new TextWebSocketFrame(last, 0, fragment), channel.voidPromise());
    return this;
}

From source file:org.asynchttpclient.providers.netty4.ws.NettyWebSocket.java

License:Open Source License

@Override
public WebSocket stream(String fragment, boolean last) {
    channel.writeAndFlush(new TextWebSocketFrame(last, 0, fragment));
    return this;
}

From source file:org.ballerinalang.test.util.websocket.client.WebSocketTestClient.java

License:Open Source License

/**
 * Send text to the server.//from ww w  .  j ava  2s  .  com
 *
 * @param text    text to be sent.
 * @param isFinal whether the text is final
 * @throws InterruptedException if connection is interrupted while sending the message.
 */
public void sendText(String text, boolean isFinal) throws InterruptedException {
    if (channel == null) {
        logger.error("Channel is null. Cannot send text.");
        throw new IllegalArgumentException("Cannot find the channel to write");
    }
    if (!isFinal) {
        if (first) {
            channel.writeAndFlush(new TextWebSocketFrame(false, 0, text)).sync();
            first = false;
        } else {
            channel.writeAndFlush(new ContinuationWebSocketFrame(false, 0, text));
        }
    } else {
        channel.writeAndFlush(new ContinuationWebSocketFrame(true, 0, text));
        first = true;
    }
}