Example usage for io.netty.handler.codec.http.websocketx WebSocketVersion V00

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

Introduction

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

Prototype

WebSocketVersion V00

To view the source code for io.netty.handler.codec.http.websocketx WebSocketVersion V00.

Click Source Link

Document

<a href= "http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00" >draft-ietf-hybi-thewebsocketprotocol- 00</a>.

Usage

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

License:Open Source License

ServerWebSocket upgrade(HttpServerRequest request, HttpRequest nettyReq) {
    if (ws != null) {
        return ws;
    }/*from  w  w w .j ava  2 s. c o m*/
    handshaker = server.createHandshaker(channel, nettyReq);
    if (handshaker == null) {
        throw new IllegalStateException("Can't upgrade this request");
    }

    ws = new ServerWebSocketImpl(vertx, request.uri(), request.path(), request.query(), request.headers(), this,
            handshaker.version() != WebSocketVersion.V00, null, server.options().getMaxWebsocketFrameSize());
    ws.setMetric(metrics.upgrade(requestMetric, ws));
    try {
        handshaker.handshake(channel, nettyReq);
    } catch (WebSocketHandshakeException e) {
        handleException(e);
    } catch (Exception e) {
        log.error("Failed to generate shake response", e);
    }
    ChannelHandler handler = channel.pipeline().get(HttpChunkContentCompressor.class);
    if (handler != null) {
        // remove compressor as its not needed anymore once connection was upgraded to websockets
        channel.pipeline().remove(handler);
    }
    server.connectionMap().put(channel, this);
    return ws;
}

From source file:io.undertow.websockets.core.protocol.AbstractWebSocketServerTest.java

License:Open Source License

@Test
public void testText() throws Exception {
    if (getVersion() == WebSocketVersion.V00) {
        // ignore 00 tests for now
        return;/*w w  w.ja v  a2s.co m*/
    }
    final AtomicBoolean connected = new AtomicBoolean(false);
    DefaultServer.setRootHandler(new WebSocketProtocolHandshakeHandler(new WebSocketConnectionCallback() {
        @Override
        public void onConnect(final WebSocketHttpExchange exchange, final WebSocketChannel channel) {
            connected.set(true);
            channel.getReceiveSetter().set(new AbstractReceiveListener() {
                @Override
                protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message)
                        throws IOException {
                    String string = message.getData();

                    if (string.equals("hello")) {
                        WebSockets.sendText("world", channel, null);
                    } else {
                        WebSockets.sendText(string, channel, null);
                    }
                }
            });
            channel.resumeReceives();
        }
    }));

    final FutureResult<?> latch = new FutureResult();
    WebSocketTestClient client = new WebSocketTestClient(getVersion(),
            new URI("ws://" + NetworkUtils.formatPossibleIpv6Address(DefaultServer.getHostAddress("default"))
                    + ":" + DefaultServer.getHostPort("default") + "/"));
    client.connect();
    client.send(new TextWebSocketFrame(Unpooled.copiedBuffer("hello", CharsetUtil.US_ASCII)),
            new FrameChecker(TextWebSocketFrame.class, "world".getBytes(CharsetUtil.US_ASCII), latch));
    latch.getIoFuture().get();
    client.destroy();
}

From source file:io.undertow.websockets.core.protocol.AbstractWebSocketServerTest.java

License:Open Source License

@Test
public void testBinary() throws Exception {
    if (getVersion() == WebSocketVersion.V00) {
        // ignore 00 tests for now
        return;/* ww w .  j ava  2  s  . c  o  m*/
    }
    final AtomicBoolean connected = new AtomicBoolean(false);
    DefaultServer.setRootHandler(new WebSocketProtocolHandshakeHandler(new WebSocketConnectionCallback() {
        @Override
        public void onConnect(final WebSocketHttpExchange exchange, final WebSocketChannel channel) {
            connected.set(true);
            channel.getReceiveSetter().set(new AbstractReceiveListener() {

                @Override
                protected void onFullBinaryMessage(WebSocketChannel channel, BufferedBinaryMessage message)
                        throws IOException {
                    final Pooled<ByteBuffer[]> data = message.getData();
                    WebSockets.sendBinary(data.getResource(), channel, new WebSocketCallback<Void>() {
                        @Override
                        public void complete(WebSocketChannel channel, Void context) {
                            data.free();
                        }

                        @Override
                        public void onError(WebSocketChannel channel, Void context, Throwable throwable) {
                            data.free();
                        }
                    });
                }
            });
            channel.resumeReceives();
        }
    }));

    final FutureResult latch = new FutureResult();
    final byte[] payload = "payload".getBytes();

    WebSocketTestClient client = new WebSocketTestClient(getVersion(),
            new URI("ws://" + NetworkUtils.formatPossibleIpv6Address(DefaultServer.getHostAddress("default"))
                    + ":" + DefaultServer.getHostPort("default") + "/"));
    client.connect();
    client.send(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(payload)),
            new FrameChecker(BinaryWebSocketFrame.class, payload, latch));
    latch.getIoFuture().get();

    client.destroy();
}

From source file:io.undertow.websockets.core.protocol.AbstractWebSocketServerTest.java

License:Open Source License

@Test
public void testCloseFrame() throws Exception {
    if (getVersion() == WebSocketVersion.V00) {
        // ignore 00 tests for now
        return;/*from   w  ww.  j ava  2s.  com*/
    }
    final AtomicBoolean connected = new AtomicBoolean(false);
    DefaultServer.setRootHandler(new WebSocketProtocolHandshakeHandler(new WebSocketConnectionCallback() {
        @Override
        public void onConnect(final WebSocketHttpExchange exchange, final WebSocketChannel channel) {
            connected.set(true);
            channel.getReceiveSetter().set(new AbstractReceiveListener() {
                @Override
                protected void onFullCloseMessage(WebSocketChannel channel, BufferedBinaryMessage message)
                        throws IOException {
                    message.getData().free();
                    channel.sendClose();
                }
            });
            channel.resumeReceives();
        }
    }));

    final AtomicBoolean receivedResponse = new AtomicBoolean(false);

    final FutureResult latch = new FutureResult();
    WebSocketTestClient client = new WebSocketTestClient(getVersion(),
            new URI("ws://" + NetworkUtils.formatPossibleIpv6Address(DefaultServer.getHostAddress("default"))
                    + ":" + DefaultServer.getHostPort("default") + "/"));
    client.connect();
    client.send(new CloseWebSocketFrame(), new FrameChecker(CloseWebSocketFrame.class, new byte[0], latch));
    latch.getIoFuture().get();
    Assert.assertFalse(receivedResponse.get());
    client.destroy();
}

From source file:io.undertow.websockets.core.protocol.AbstractWebSocketServerTest.java

License:Open Source License

protected WebSocketVersion getVersion() {
    return WebSocketVersion.V00;
}

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

License:Open Source License

synchronized void toWebSocket(String requestURI, MultiMap headers, WebsocketVersion vers, String subProtocols,
        int maxWebSocketFrameSize, Handler<WebSocket> wsConnect) {
    if (ws != null) {
        throw new IllegalStateException("Already websocket");
    }//from  w w w.jav a  2  s.  c o  m

    try {
        URI wsuri = new URI(requestURI);
        if (!wsuri.isAbsolute()) {
            // Netty requires an absolute url
            wsuri = new URI((ssl ? "https:" : "http:") + "//" + host + ":" + port + requestURI);
        }
        WebSocketVersion version = WebSocketVersion
                .valueOf((vers == null ? WebSocketVersion.V13 : vers).toString());
        HttpHeaders nettyHeaders;
        if (headers != null) {
            nettyHeaders = new DefaultHttpHeaders();
            for (Map.Entry<String, String> entry : headers) {
                nettyHeaders.add(entry.getKey(), entry.getValue());
            }
        } else {
            nettyHeaders = null;
        }
        handshaker = WebSocketClientHandshakerFactory.newHandshaker(wsuri, version, subProtocols, false,
                nettyHeaders, maxWebSocketFrameSize, !client.getOptions().isSendUnmaskedFrames(), false);
        ChannelPipeline p = channel.pipeline();
        p.addBefore("handler", "handshakeCompleter",
                new HandshakeInboundHandler(wsConnect, version != WebSocketVersion.V00));
        handshaker.handshake(channel).addListener(future -> {
            Handler<Throwable> handler = exceptionHandler();
            if (!future.isSuccess() && handler != null) {
                handler.handle(future.cause());
            }
        });
    } catch (Exception e) {
        handleException(e);
    }
}

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

License:Open Source License

synchronized void toWebSocket(String requestURI, MultiMap headers, WebsocketVersion vers, String subProtocols,
        int maxWebSocketFrameSize, Handler<WebSocket> wsConnect) {
    if (ws != null) {
        throw new IllegalStateException("Already websocket");
    }/*from w w  w  .ja  v  a2  s  .  co m*/

    try {
        URI wsuri = new URI(requestURI);
        if (!wsuri.isAbsolute()) {
            // Netty requires an absolute url
            wsuri = new URI((ssl ? "https:" : "http:") + "//" + host + ":" + port + requestURI);
        }
        WebSocketVersion version = WebSocketVersion
                .valueOf((vers == null ? WebSocketVersion.V13 : vers).toString());
        HttpHeaders nettyHeaders;
        if (headers != null) {
            nettyHeaders = new DefaultHttpHeaders();
            for (Map.Entry<String, String> entry : headers) {
                nettyHeaders.add(entry.getKey(), entry.getValue());
            }
        } else {
            nettyHeaders = null;
        }

        ChannelPipeline p = chctx.channel().pipeline();
        ArrayList<WebSocketClientExtensionHandshaker> extensionHandshakers = initializeWebsocketExtensionHandshakers(
                client.getOptions());
        if (!extensionHandshakers.isEmpty()) {
            p.addBefore("handler", "websocketsExtensionsHandler",
                    new WebSocketClientExtensionHandler(extensionHandshakers
                            .toArray(new WebSocketClientExtensionHandshaker[extensionHandshakers.size()])));
        }

        handshaker = WebSocketClientHandshakerFactory.newHandshaker(wsuri, version, subProtocols,
                !extensionHandshakers.isEmpty(), nettyHeaders, maxWebSocketFrameSize,
                !options.isSendUnmaskedFrames(), false);

        p.addBefore("handler", "handshakeCompleter",
                new HandshakeInboundHandler(wsConnect, version != WebSocketVersion.V00));
        handshaker.handshake(chctx.channel()).addListener(future -> {
            Handler<Throwable> handler = exceptionHandler();
            if (!future.isSuccess() && handler != null) {
                handler.handle(future.cause());
            }
        });
    } catch (Exception e) {
        handleException(e);
    }
}

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

License:Open Source License

ServerWebSocketImpl createWebSocket(HttpServerRequestImpl request) {
    if (ws != null) {
        return ws;
    }//from   ww w . ja v a  2  s.c  o m
    if (!(request.getRequest() instanceof FullHttpRequest)) {
        throw new IllegalStateException();
    }
    FullHttpRequest nettyReq = (FullHttpRequest) request.getRequest();
    WebSocketServerHandshaker handshaker = createHandshaker(nettyReq);
    if (handshaker == null) {
        throw new IllegalStateException("Can't upgrade this request");
    }
    Function<ServerWebSocketImpl, String> f = ws -> {
        try {
            handshaker.handshake(chctx.channel(), nettyReq);
        } catch (WebSocketHandshakeException e) {
            handleException(e);
        } catch (Exception e) {
            log.error("Failed to generate shake response", e);
        }
        // remove compressor as its not needed anymore once connection was upgraded to websockets
        ChannelHandler handler = chctx.pipeline().get(HttpChunkContentCompressor.class);
        if (handler != null) {
            chctx.pipeline().remove(handler);
        }
        if (METRICS_ENABLED && metrics != null) {
            ws.setMetric(metrics.upgrade(request.metric(), ws));
        }
        ws.registerHandler(vertx.eventBus());
        return handshaker.selectedSubprotocol();
    };
    ws = new ServerWebSocketImpl(vertx, request.uri(), request.path(), request.query(), request.headers(), this,
            handshaker.version() != WebSocketVersion.V00, f, options.getMaxWebsocketFrameSize(),
            options.getMaxWebsocketMessageSize());
    return ws;
}

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

License:Open Source License

ServerWebSocket upgrade(HttpServerRequest request, HttpRequest nettyReq) {
    if (ws != null) {
        return ws;
    }//  ww w.  ja v  a2s  .c o  m
    handshaker = server.createHandshaker(channel, nettyReq);
    if (handshaker == null) {
        throw new IllegalStateException("Can't upgrade this request");
    }

    ws = new ServerWebSocketImpl(vertx, request.uri(), request.path(), request.query(), request.headers(), this,
            handshaker.version() != WebSocketVersion.V00, null, server.options().getMaxWebsocketFrameSize(),
            server.options().getMaxWebsocketMessageSize());
    ws.setMetric(metrics.upgrade(requestMetric, ws));
    try {
        handshaker.handshake(channel, nettyReq);
    } catch (WebSocketHandshakeException e) {
        handleException(e);
    } catch (Exception e) {
        log.error("Failed to generate shake response", e);
    }
    ChannelHandler handler = channel.pipeline().get(HttpChunkContentCompressor.class);
    if (handler != null) {
        // remove compressor as its not needed anymore once connection was upgraded to websockets
        channel.pipeline().remove(handler);
    }
    server.connectionMap().put(channel, this);
    return ws;
}