Example usage for io.netty.handler.codec.http.websocketx WebSocketServerHandshaker selectedSubprotocol

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

Introduction

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

Prototype

String selectedSubprotocol

To view the source code for io.netty.handler.codec.http.websocketx WebSocketServerHandshaker selectedSubprotocol.

Click Source Link

Usage

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

License:Open Source License

ServerWebSocketImpl createWebSocket(HttpServerRequestImpl request) {
    if (ws != null) {
        return ws;
    }//from w  w  w  .  j  av a 2s . 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:org.wso2.carbon.transport.http.netty.contractimpl.websocket.message.WebSocketInitMessageImpl.java

License:Open Source License

private HandshakeFuture handleHandshake(WebSocketServerHandshaker handshaker, int idleTimeout) {
    HandshakeFutureImpl handshakeFuture = new HandshakeFutureImpl();

    if (isCancelled) {
        Throwable e = new IllegalAccessException("Handshake is already cancelled!");
        handshakeFuture.notifyError(e);/*from   w ww  .  j a v  a  2 s  .  c om*/
        return handshakeFuture;
    }

    try {
        ChannelFuture future = handshaker.handshake(ctx.channel(), httpRequest);
        handshakeFuture.setChannelFuture(future);
        future.addListener(new GenericFutureListener<Future<? super Void>>() {
            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
                String selectedSubProtocol = handshaker.selectedSubprotocol();
                webSocketSourceHandler.setNegotiatedSubProtocol(selectedSubProtocol);
                setSubProtocol(selectedSubProtocol);
                WebSocketSessionImpl session = (WebSocketSessionImpl) getChannelSession();
                session.setIsOpen(true);
                session.setNegotiatedSubProtocol(selectedSubProtocol);

                //Replace HTTP handlers  with  new Handlers for WebSocket in the pipeline
                ChannelPipeline pipeline = ctx.pipeline();

                if (idleTimeout > 0) {
                    pipeline.replace(Constants.IDLE_STATE_HANDLER, Constants.IDLE_STATE_HANDLER,
                            new IdleStateHandler(idleTimeout, idleTimeout, idleTimeout, TimeUnit.MILLISECONDS));
                } else {
                    pipeline.remove(Constants.IDLE_STATE_HANDLER);
                }
                pipeline.addLast(Constants.WEBSOCKET_SOURCE_HANDLER, webSocketSourceHandler);
                pipeline.remove(Constants.HTTP_SOURCE_HANDLER);
                setProperty(Constants.SRC_HANDLER, webSocketSourceHandler);
                handshakeFuture.notifySuccess(webSocketSourceHandler.getChannelSession());
            }
        });
        return handshakeFuture;
    } catch (Exception e) {
        /*
        Code 1002 : indicates that an endpoint is terminating the connection
        due to a protocol error.
         */
        handshaker.close(ctx.channel(),
                new CloseWebSocketFrame(1002, "Terminating the connection due to a protocol error."));
        handshakeFuture.notifyError(e);
        return handshakeFuture;
    }
}

From source file:ws.wamp.jawampa.transport.netty.WampServerWebsocketHandler.java

License:Apache License

private void tryWebsocketHandshake(final ChannelHandlerContext ctx, FullHttpRequest request) {
    String wsLocation = getWebSocketLocation(ctx, request);
    String subProtocols = WampSerialization.makeWebsocketSubprotocolList(supportedSerializations);
    WebSocketServerHandshaker handshaker = new WebSocketServerHandshakerFactory(wsLocation, subProtocols, false,
            WampHandlerConfiguration.MAX_WEBSOCKET_FRAME_SIZE).newHandshaker(request);

    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {/*from w  ww.j av a2  s  .c o  m*/
        handshakeInProgress = true;
        // The next statement will throw if the handshake gets wrong. This will lead to an
        // exception in the channel which will close the channel (which is OK).
        final ChannelFuture handshakeFuture = handshaker.handshake(ctx.channel(), request);
        String actualProtocol = handshaker.selectedSubprotocol();
        serialization = WampSerialization.fromString(actualProtocol);

        // In case of unsupported websocket subprotocols we close the connection.
        // Won't help us when the client will ignore our protocol response and send
        // invalid packets anyway
        if (serialization == WampSerialization.Invalid) {
            handshakeFuture.addListener(ChannelFutureListener.CLOSE);
            return;
        }

        // Remove all handlers after this one - we don't need them anymore since we switch to WAMP
        ChannelHandler last = ctx.pipeline().last();
        while (last != null && last != this) {
            ctx.pipeline().removeLast();
            last = ctx.pipeline().last();
        }

        if (last == null) {
            throw new IllegalStateException("Can't find the WAMP server handler in the pipeline");
        }

        // Remove the WampServerWebSocketHandler and replace it with the protocol handler
        // which processes pings and closes
        ProtocolHandler protocolHandler = new ProtocolHandler();
        ctx.pipeline().replace(this, "wamp-websocket-protocol-handler", protocolHandler);
        final ChannelHandlerContext protocolHandlerCtx = ctx.pipeline().context(protocolHandler);

        // Handle websocket fragmentation before the deserializer
        protocolHandlerCtx.pipeline()
                .addLast(new WebSocketFrameAggregator(WampHandlerConfiguration.MAX_WEBSOCKET_FRAME_SIZE));

        // Install the serializer and deserializer
        protocolHandlerCtx.pipeline().addLast("wamp-serializer", new WampSerializationHandler(serialization));
        protocolHandlerCtx.pipeline().addLast("wamp-deserializer",
                new WampDeserializationHandler(serialization));

        // Retrieve a listener for this new connection
        final IWampConnectionListener connectionListener = connectionAcceptor.createNewConnectionListener();

        // Create a Wamp connection interface on top of that
        final WampServerConnection connection = new WampServerConnection(serialization);

        ChannelHandler routerHandler = new SimpleChannelInboundHandler<WampMessage>() {
            @Override
            public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
                // Gets called once the channel gets added to the pipeline
                connection.ctx = ctx;
            }

            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                connectionAcceptor.acceptNewConnection(connection, connectionListener);
            }

            @Override
            public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                connectionListener.transportClosed();
            }

            @Override
            protected void channelRead0(ChannelHandlerContext ctx, WampMessage msg) throws Exception {
                connectionListener.messageReceived(msg);
            }

            @Override
            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                ctx.close();
                connectionListener.transportError(cause);
            }
        };

        // Install the router in the pipeline
        protocolHandlerCtx.pipeline().addLast("wamp-router", routerHandler);

        handshakeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    // The handshake was not successful. 
                    // Close the channel without registering
                    ctx.fireExceptionCaught(future.cause()); // TODO: This is a race condition if the router did not yet accept the connection
                } else {
                    // We successfully sent out the handshake
                    // Notify the router of that fact
                    ctx.fireChannelActive();
                }
            }
        });

        // TODO: Maybe there are frames incoming before the handshakeFuture is resolved
        // This might lead to frames getting sent to the router before it is activated
    }
}

From source file:ws.wamp.jawampa.transport.WampServerWebsocketHandler.java

License:Apache License

private void tryWebsocketHandshake(final ChannelHandlerContext ctx, FullHttpRequest request) {
    String wsLocation = getWebSocketLocation(ctx, request);
    WebSocketServerHandshaker handshaker = new WebSocketServerHandshakerFactory(wsLocation,
            WampHandlerConfiguration.WAMP_WEBSOCKET_PROTOCOLS, false,
            WampHandlerConfiguration.MAX_WEBSOCKET_FRAME_SIZE).newHandshaker(request);

    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {//from   w w w . j a  v  a 2 s. c o m
        handshakeInProgress = true;
        final ChannelFuture handshakeFuture = handshaker.handshake(ctx.channel(), request);
        String actualProtocol = handshaker.selectedSubprotocol();
        if (actualProtocol != null && actualProtocol.equals("wamp.2.json")) {
            serialization = Serialization.Json;
        }
        //            else if (actualProtocol.equals("wamp.2.msgpack")) {
        //                serialization = Serialization.MessagePack;
        //            }

        // In case of unsupported websocket subprotocols we close the connection.
        // Won't help us when the client will ignore our protocol response and send
        // invalid packets anyway
        if (serialization == Serialization.Invalid) {
            handshakeFuture.addListener(ChannelFutureListener.CLOSE);
            return;
        }

        // Remove all handlers after this one - we don't need them anymore since we switch to WAMP
        ChannelHandler last = ctx.pipeline().last();
        while (last != null && last != this) {
            ctx.pipeline().removeLast();
            last = ctx.pipeline().last();
        }

        if (last == null) {
            throw new IllegalStateException("Can't find the WAMP server handler in the pipeline");
        }

        // Remove the WampServerWebSocketHandler and replace it with the protocol handler
        // which processes pings and closes
        ProtocolHandler protocolHandler = new ProtocolHandler();
        ctx.pipeline().replace(this, "wamp-websocket-protocol-handler", protocolHandler);
        final ChannelHandlerContext protocolHandlerCtx = ctx.pipeline().context(protocolHandler);

        // Handle websocket fragmentation before the deserializer
        protocolHandlerCtx.pipeline()
                .addLast(new WebSocketFrameAggregator(WampHandlerConfiguration.MAX_WEBSOCKET_FRAME_SIZE));

        // Install the serializer and deserializer
        protocolHandlerCtx.pipeline().addLast("wamp-serializer",
                new WampSerializationHandler(serialization, router.objectMapper()));
        protocolHandlerCtx.pipeline().addLast("wamp-deserializer",
                new WampDeserializationHandler(serialization, router.objectMapper()));

        // Install the router in the pipeline
        protocolHandlerCtx.pipeline().addLast(router.eventLoop(), "wamp-router", router.createRouterHandler());

        handshakeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    ctx.fireExceptionCaught(future.cause());
                } else {
                    // We successfully sent out the handshake
                    // Notify the activation to everything new
                    ctx.fireChannelActive();
                }
            }
        });
    }
}