Search in sources :

Example 1 with TextWebSocketFrame

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

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

the class WebSocketFrameHandler method channelRead0.

@Override
protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
    if (frame instanceof TextWebSocketFrame) {
        // Send the uppercase string back.
        String request = ((TextWebSocketFrame) frame).text();
        logger.info("{} received {}", ctx.channel(), request);
        ctx.channel().writeAndFlush(new TextWebSocketFrame(request.toUpperCase(Locale.US)));
    } else {
        String message = "unsupported frame type: " + frame.getClass().getName();
        throw new UnsupportedOperationException(message);
    }
}
Also used : TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame)

Example 3 with TextWebSocketFrame

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

the class DeflateDecoder method decode.

@Override
protected void decode(ChannelHandlerContext ctx, WebSocketFrame msg, List<Object> out) throws Exception {
    if (decoder == null) {
        if (!(msg instanceof TextWebSocketFrame) && !(msg instanceof BinaryWebSocketFrame)) {
            throw new CodecException("unexpected initial frame type: " + msg.getClass().getName());
        }
        decoder = new EmbeddedChannel(ZlibCodecFactory.newZlibDecoder(ZlibWrapper.NONE));
    }
    boolean readable = msg.content().isReadable();
    decoder.writeInbound(msg.content().retain());
    if (appendFrameTail(msg)) {
        decoder.writeInbound(Unpooled.wrappedBuffer(FRAME_TAIL));
    }
    CompositeByteBuf compositeUncompressedContent = ctx.alloc().compositeBuffer();
    for (; ; ) {
        ByteBuf partUncompressedContent = decoder.readInbound();
        if (partUncompressedContent == null) {
            break;
        }
        if (!partUncompressedContent.isReadable()) {
            partUncompressedContent.release();
            continue;
        }
        compositeUncompressedContent.addComponent(true, partUncompressedContent);
    }
    // See https://github.com/netty/netty/issues/4348
    if (readable && compositeUncompressedContent.numComponents() <= 0) {
        compositeUncompressedContent.release();
        throw new CodecException("cannot read uncompressed buffer");
    }
    if (msg.isFinalFragment() && noContext) {
        cleanup();
    }
    WebSocketFrame outMsg;
    if (msg instanceof TextWebSocketFrame) {
        outMsg = new TextWebSocketFrame(msg.isFinalFragment(), newRsv(msg), compositeUncompressedContent);
    } else if (msg instanceof BinaryWebSocketFrame) {
        outMsg = new BinaryWebSocketFrame(msg.isFinalFragment(), newRsv(msg), compositeUncompressedContent);
    } else if (msg instanceof ContinuationWebSocketFrame) {
        outMsg = new ContinuationWebSocketFrame(msg.isFinalFragment(), newRsv(msg), compositeUncompressedContent);
    } else {
        throw new CodecException("unexpected frame type: " + msg.getClass().getName());
    }
    out.add(outMsg);
}
Also used : CompositeByteBuf(io.netty.buffer.CompositeByteBuf) ContinuationWebSocketFrame(io.netty.handler.codec.http.websocketx.ContinuationWebSocketFrame) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) BinaryWebSocketFrame(io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) CodecException(io.netty.handler.codec.CodecException) 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) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) ByteBuf(io.netty.buffer.ByteBuf)

Example 4 with TextWebSocketFrame

use of io.netty.handler.codec.http.websocketx.TextWebSocketFrame in project async-http-client by AsyncHttpClient.

the class NettyWebSocket method sendMessage.

@Override
public WebSocket sendMessage(String message, WebSocketWriteCompleteListener listener) {
    final ChannelPromise channelPromise = channel.newPromise();
    channelPromise.addListener(listener);
    channel.writeAndFlush(new TextWebSocketFrame(message), channelPromise);
    return this;
}
Also used : TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) ChannelPromise(io.netty.channel.ChannelPromise)

Example 5 with TextWebSocketFrame

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

the class DynamicEndpointTest method testDynamicAnnotatedEndpoint.

@Test
public void testDynamicAnnotatedEndpoint() throws Exception {
    final byte[] payload = "hello".getBytes();
    final FutureResult latch = new FutureResult();
    WebSocketTestClient client = new WebSocketTestClient(WebSocketVersion.V13, new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/ws/dynamicEchoEndpoint?annotated=true"));
    client.connect();
    client.send(new TextWebSocketFrame(Unpooled.wrappedBuffer(payload)), new FrameChecker(TextWebSocketFrame.class, "opened:true /dynamicEchoEndpoint hello".getBytes(), latch));
    latch.getIoFuture().get();
    client.destroy();
}
Also used : WebSocketTestClient(io.undertow.websockets.utils.WebSocketTestClient) FutureResult(org.xnio.FutureResult) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) FrameChecker(io.undertow.websockets.utils.FrameChecker) URI(java.net.URI) Test(org.junit.Test)

Aggregations

TextWebSocketFrame (io.netty.handler.codec.http.websocketx.TextWebSocketFrame)26 URI (java.net.URI)16 FrameChecker (io.undertow.websockets.utils.FrameChecker)15 WebSocketTestClient (io.undertow.websockets.utils.WebSocketTestClient)15 Test (org.junit.Test)15 FutureResult (org.xnio.FutureResult)15 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)7 BinaryWebSocketFrame (io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame)5 CloseWebSocketFrame (io.netty.handler.codec.http.websocketx.CloseWebSocketFrame)5 WebSocketFrame (io.netty.handler.codec.http.websocketx.WebSocketFrame)5 ServerWebSocketContainer (io.undertow.websockets.jsr.ServerWebSocketContainer)5 UndertowSession (io.undertow.websockets.jsr.UndertowSession)5 AnnotatedClientEndpoint (io.undertow.websockets.jsr.test.annotated.AnnotatedClientEndpoint)5 ByteBuf (io.netty.buffer.ByteBuf)4 IOException (java.io.IOException)4 AtomicReference (java.util.concurrent.atomic.AtomicReference)4 Endpoint (javax.websocket.Endpoint)4 EndpointConfig (javax.websocket.EndpointConfig)4 MessageHandler (javax.websocket.MessageHandler)4 Session (javax.websocket.Session)4