Example usage for io.netty.handler.codec.http.websocketx WebSocketClientHandshakerFactory newHandshaker

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

Introduction

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

Prototype

public static WebSocketClientHandshaker newHandshaker(URI webSocketURL, WebSocketVersion version,
        String subprotocol, boolean allowExtensions, HttpHeaders customHeaders, int maxFramePayloadLength) 

Source Link

Document

Creates a new handshaker.

Usage

From source file:cn.scujcc.bug.bitcoinplatformandroid.util.socket.websocket.WebSocketBase.java

License:Apache License

private void connect() {
    try {/* ww w.j  a  v  a  2 s. co m*/
        final URI uri = new URI(url);
        if (uri == null) {
            return;
        }
        if (uri.getHost().contains("com")) {
            siteFlag = 1;
        }
        group = new NioEventLoopGroup(1);
        bootstrap = new Bootstrap();
        final SslContext sslCtx = SslContext.newClientContext();
        final WebSocketClientHandler handler = new WebSocketClientHandler(
                WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false,
                        new DefaultHttpHeaders(), Integer.MAX_VALUE),
                service, moniter);
        bootstrap.group(group).option(ChannelOption.TCP_NODELAY, true).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc(), uri.getHost(), uri.getPort()));
                        }
                        p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler);
                    }
                });

        future = bootstrap.connect(uri.getHost(), uri.getPort());
        future.addListener(new ChannelFutureListener() {
            public void operationComplete(final ChannelFuture future) throws Exception {
            }
        });
        channel = future.sync().channel();
        handler.handshakeFuture().sync();
        this.setStatus(true);
    } catch (Exception e) {
        Log.e(TAG, "WebSocketClient start error " + e.getLocalizedMessage());
        group.shutdownGracefully();
        this.setStatus(false);
    }
}

From source file:com.intuit.karate.netty.WebSocketClientInitializer.java

License:Open Source License

public WebSocketClientInitializer(WebSocketOptions options, WebSocketListener listener) {
    this.uri = options.getUri();
    this.port = options.getPort();
    if (options.isSsl()) {
        try {/*from  w ww . j a va2 s .  co m*/
            sslContext = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
                    .build();
        } catch (SSLException e) {
            throw new RuntimeException(e);
        }
    } else {
        sslContext = null;
    }
    HttpHeaders nettyHeaders = new DefaultHttpHeaders();
    Map<String, Object> headers = options.getHeaders();
    if (headers != null) {
        headers.forEach((k, v) -> nettyHeaders.add(k, v));
    }
    WebSocketClientHandshaker handShaker = WebSocketClientHandshakerFactory.newHandshaker(uri,
            WebSocketVersion.V13, options.getSubProtocol(), true, nettyHeaders, options.getMaxPayloadSize());
    handler = new WebSocketClientHandler(handShaker, listener);
}

From source file:io.advantageous.conekt.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  om

    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);
        ChannelPipeline p = channel.pipeline();
        p.addBefore("handler", "handshakeCompleter",
                new HandshakeInboundHandler(wsConnect, version != WebSocketVersion.V00));
        handshaker.handshake(channel).addListener(future -> {
            if (!future.isSuccess() && exceptionHandler != null) {
                exceptionHandler.handle(future.cause());
            }
        });
    } catch (Exception e) {
        handleException(e);
    }
}

From source file:io.crossbar.autobahn.wamp.transports.NettyWebSocket.java

License:MIT License

@Override
public void connect(ITransportHandler transportHandler, TransportOptions options) throws Exception {

    if (options == null) {
        if (mOptions == null) {
            options = new TransportOptions();
        } else {/*from  w  w w .j  a v a  2  s . c  o m*/
            options = new TransportOptions();
            options.setAutoPingInterval(mOptions.getAutoPingInterval());
            options.setAutoPingTimeout(mOptions.getAutoPingTimeout());
            options.setMaxFramePayloadSize(mOptions.getMaxFramePayloadSize());
        }
    }

    URI uri;
    uri = new URI(mUri);
    int port = validateURIAndGetPort(uri);
    String scheme = uri.getScheme();
    String host = uri.getHost();

    final SslContext sslContext = getSSLContext(scheme);

    WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri,
            WebSocketVersion.V13, mSerializers, true, new DefaultHttpHeaders(),
            options.getMaxFramePayloadSize());
    mHandler = new NettyWebSocketClientHandler(handshaker, this, transportHandler);

    EventLoopGroup group = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group);
    bootstrap.channel(NioSocketChannel.class);

    TransportOptions opt = options;
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline channelPipeline = ch.pipeline();
            if (sslContext != null) {
                channelPipeline.addLast(sslContext.newHandler(ch.alloc(), host, port));
            }
            channelPipeline.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192),
                    WebSocketClientCompressionHandler.INSTANCE,
                    new IdleStateHandler(opt.getAutoPingInterval() + opt.getAutoPingTimeout(),
                            opt.getAutoPingInterval(), 0, TimeUnit.SECONDS),
                    mHandler);
        }
    });

    mChannel = bootstrap.connect(uri.getHost(), port).sync().channel();
    mHandler.getHandshakeFuture().sync();
}

From source file:io.gatling.http.client.impl.WebSocketHandler.java

License:Apache License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
    if (msg instanceof HttpTx) {

        HttpTx tx = (HttpTx) msg;//from  w w  w  .  j a va 2 s. com
        setActive(tx);

        if (tx.requestTimeout.isDone()) {
            return;
        }

        try {
            WritableRequest request = WritableRequestBuilder.buildRequest(tx.request, ctx.alloc(), config,
                    false);

            handshaker = WebSocketClientHandshakerFactory.newHandshaker(tx.request.getUri().toJavaNetURI(),
                    WebSocketVersion.V13, null, true, request.getRequest().headers(),
                    config.getWebSocketMaxFramePayloadLength());

            handshaker.handshake(ctx.channel());

        } catch (Exception e) {
            crash(ctx, e, true);
        }
    } else {
        // all other messages are CONNECT request and WebSocket frames
        LOGGER.debug("ctx.write msg={}", msg);
        ctx.write(msg, promise);
    }
}

From source file:io.higgs.ws.client.WebSocketClient.java

License:Apache License

public WebSocketClient(URI uri, Map<String, Object> customHeaders, boolean autoPong, String[] sslProtocols) {
    super(BUILDER, HttpRequestBuilder.group(), uri, HttpMethod.GET, HttpVersion.HTTP_1_1, new PageReader());
    final String protocol = uri.getScheme();
    if (!"ws".equals(protocol) && !"wss".equals(protocol)) {
        throw new IllegalArgumentException("Unsupported protocol: " + protocol);
    }//from   ww  w.  ja va  2s  . c  o  m
    if (customHeaders != null) {
        for (Map.Entry<String, Object> e : customHeaders.entrySet()) {
            customHeaderSet.add(e.getKey(), e.getValue());
        }
    }
    handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri, version, subprotocol, allowExtensions,
            customHeaderSet, maxFramePayloadLength);
    handler = new WebSocketClientHandler(handshaker, listeners, autoPong);
    this.autoPong = autoPong;
    this.sslProtocols = sslProtocols == null || sslProtocols.length == 0
            ? HttpRequestBuilder.getSupportedSSLProtocols()
            : sslProtocols;
}

From source file:io.jsync.http.impl.ClientConnection.java

License:Open Source License

void toWebSocket(String uri, final WebSocketVersion wsVersion, final MultiMap headers,
        int maxWebSocketFrameSize, final Set<String> subProtocols, final Handler<WebSocket> wsConnect) {
    if (ws != null) {
        throw new IllegalStateException("Already websocket");
    }//from w w w .j  a  v a  2  s  . c  o m

    try {
        URI wsuri = new URI(uri);
        if (!wsuri.isAbsolute()) {
            // Netty requires an absolute url
            wsuri = new URI((ssl ? "https:" : "http:") + "//" + host + ":" + port + uri);
        }
        io.netty.handler.codec.http.websocketx.WebSocketVersion version;
        if (wsVersion == WebSocketVersion.HYBI_00) {
            version = io.netty.handler.codec.http.websocketx.WebSocketVersion.V00;
        } else if (wsVersion == WebSocketVersion.HYBI_08) {
            version = io.netty.handler.codec.http.websocketx.WebSocketVersion.V08;
        } else if (wsVersion == WebSocketVersion.RFC6455) {
            version = io.netty.handler.codec.http.websocketx.WebSocketVersion.V13;
        } else {
            throw new IllegalArgumentException("Invalid version");
        }
        HttpHeaders nettyHeaders;
        if (headers != null) {
            nettyHeaders = new DefaultHttpHeaders();
            for (Map.Entry<String, String> entry : headers) {
                nettyHeaders.add(entry.getKey(), entry.getValue());
            }
        } else {
            nettyHeaders = null;
        }
        String wsSubProtocols = null;
        if (subProtocols != null && !subProtocols.isEmpty()) {
            StringBuilder sb = new StringBuilder();

            Iterator<String> protocols = subProtocols.iterator();
            while (protocols.hasNext()) {
                sb.append(protocols.next());
                if (protocols.hasNext()) {
                    sb.append(",");
                }
            }
            wsSubProtocols = sb.toString();
        }
        handshaker = WebSocketClientHandshakerFactory.newHandshaker(wsuri, version, wsSubProtocols, false,
                nettyHeaders, maxWebSocketFrameSize);
        final ChannelPipeline p = channel.pipeline();
        p.addBefore("handler", "handshakeCompleter", new HandshakeInboundHandler(wsConnect));
        handshaker.handshake(channel).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    client.handleException((Exception) future.cause());
                }
            }
        });
        upgradedConnection = true;

    } catch (Exception e) {
        handleException(e);
    }
}

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

License:Apache License

@Override
public void configureNewPipeline(ChannelPipeline pipeline) {
    WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(webSocketURI,
            webSocketVersion, subprotocol, allowExtensions, new DefaultHttpHeaders(), maxFramePayloadLength);
    WebSocketClientHandler handler = new WebSocketClientHandler(handshaker, maxFramePayloadLength,
            messageAggregation, eventsSubject);
    pipeline.addLast(new HttpClientCodec());
    pipeline.addLast(new HttpObjectAggregator(8192));
    pipeline.addLast(handler);/*from  w  w  w. ja v a  2  s.  c o  m*/
}

From source file:no.nb.nna.broprox.chrome.client.ws.WebsocketClient.java

License:Apache License

private void connect() {
    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;//from   www .  j  av  a  2s .co  m
        } 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) {
        try {
            sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        } catch (SSLException ex) {
            throw new RuntimeException(ex);
        }
    } else {
        sslCtx = null;
    }

    workerGroup = new NioEventLoopGroup();

    try {
        final WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri,
                WebSocketVersion.V13, null, true, new DefaultHttpHeaders(), MAX_FRAME_PAYLOAD_LENGTH);
        //                    uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders(), MAX_FRAME_PAYLOAD_LENGTH, true, true);

        final ResponseHandler handler = new ResponseHandler();

        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.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),
                        new WebSocketClientProtocolHandler(handshaker, false), handler);
            }

        });

        channel = b.connect(uri.getHost(), port).sync().channel();

        handler.handshakeFuture().sync();

    } catch (InterruptedException ex) {
        throw new RuntimeException(ex);
    }

}

From source file:org.apache.tinkerpop.gremlin.driver.simple.WebSocketClient.java

License:Apache License

public WebSocketClient(final URI uri) {
    super("ws-client-%d");
    final Bootstrap b = new Bootstrap().group(group);
    b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    final String protocol = uri.getScheme();
    if (!"ws".equals(protocol))
        throw new IllegalArgumentException("Unsupported protocol: " + protocol);

    try {//from  w  w  w . j  a  v a 2 s . c  om
        final WebSocketClientHandler wsHandler = new WebSocketClientHandler(WebSocketClientHandshakerFactory
                .newHandshaker(uri, WebSocketVersion.V13, null, false, HttpHeaders.EMPTY_HEADERS, 65536));
        final MessageSerializer serializer = new GryoMessageSerializerV1d0();
        b.channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(final SocketChannel ch) {
                final ChannelPipeline p = ch.pipeline();
                p.addLast(new HttpClientCodec(), new HttpObjectAggregator(65536), wsHandler,
                        new WebSocketGremlinRequestEncoder(true, serializer),
                        new WebSocketGremlinResponseDecoder(serializer), callbackResponseHandler);
            }
        });

        channel = b.connect(uri.getHost(), uri.getPort()).sync().channel();
        wsHandler.handshakeFuture().get(10000, TimeUnit.MILLISECONDS);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}