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) 

Source Link

Document

Creates a new handshaker.

Usage

From source file:be.yildizgames.module.network.netty.client.SimpleWebSocketClientHandler.java

License:MIT License

@Override
public void channelActive(ChannelHandlerContext ctx) throws URISyntaxException {
    String host = ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress();
    int port = ((InetSocketAddress) ctx.channel().remoteAddress()).getPort();
    String uri = "ws://" + host + ":" + port + "/websocket";
    this.handshaker = WebSocketClientHandshakerFactory.newHandshaker(new URI(uri), WebSocketVersion.V13, null,
            false, new DefaultHttpHeaders());
    this.handshaker.handshake(ctx.channel());
}

From source file:c5db.client.C5NettyConnectionManager.java

License:Apache License

Channel connect(String host, int port) throws InterruptedException, TimeoutException, ExecutionException {
    final WebSocketClientHandshaker handShaker = WebSocketClientHandshakerFactory.newHandshaker(uri,
            WebSocketVersion.V13, null, false, new DefaultHttpHeaders());
    final C5ConnectionInitializer initializer = new C5ConnectionInitializer(handShaker);
    bootstrap.channel(NioSocketChannel.class).handler(initializer);

    final ChannelFuture future = bootstrap.connect(host, port);
    final Channel channel = future.sync().channel();
    initializer.syncOnHandshake();//from  w ww.  j a  va  2s .com

    return channel;
}

From source file:ca.lambtoncollege.netty.webSocket.ClientWebSocket.java

public static void main(String[] args) throws Exception {
    URI uri = new URI(URL);
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    final int port;
    if (uri.getPort() == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;//from  w  ww  . j a v  a 2 s. c om
        } else if ("https".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 = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } 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 ClientHandlerWebSocket handler = new ClientHandlerWebSocket(WebSocketClientHandshakerFactory
                .newHandshaker(uri, WebSocketVersion.V13, null, false, 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), 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();
    }
}

From source file:cc.blynk.integration.model.websocket.AppWebSocketClient.java

License:Apache License

public AppWebSocketClient(String host, int port, String path) throws Exception {
    super(host, port, new Random(), new ServerProperties(Collections.emptyMap()));

    URI uri = new URI("wss://" + host + ":" + port + path);
    this.sslCtx = SslContextBuilder.forClient().sslProvider(SslProvider.JDK)
            .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    this.appHandler = new AppWebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(uri,
            WebSocketVersion.V13, null, false, new DefaultHttpHeaders()));
}

From source file:cc.blynk.integration.model.websocket.WebSocketClient.java

License:Apache License

public WebSocketClient(String host, int port, boolean isSSL) throws Exception {
    super(host, port, new Random());

    String scheme = isSSL ? "wss://" : "ws://";
    URI uri = new URI(scheme + host + ":" + port + WebSocketHandler.WEBSOCKET_PATH);

    if (isSSL) {/*from www . j a  v  a  2  s .  c  om*/
        sslCtx = SslContextBuilder.forClient().sslProvider(SslProvider.JDK)
                .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    this.handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(uri,
            WebSocketVersion.V13, null, false, new DefaultHttpHeaders()));
}

From source file:cf.dropsonde.firehose.NettyFirehoseOnSubscribe.java

License:Open Source License

public NettyFirehoseOnSubscribe(URI uri, String token, String subscriptionId, boolean skipTlsValidation,
        EventLoopGroup eventLoopGroup, Class<? extends SocketChannel> channelClass) {
    try {/*from   w ww  .java 2s.c  o m*/
        final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
        final String scheme = uri.getScheme() == null ? "ws" : uri.getScheme();
        final int port = getPort(scheme, uri.getPort());
        final URI fullUri = uri.resolve("/firehose/" + subscriptionId);

        final SslContext sslContext;
        if ("wss".equalsIgnoreCase(scheme)) {
            final SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();
            if (skipTlsValidation) {
                sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
            } else {
                TrustManagerFactory trustManagerFactory = TrustManagerFactory
                        .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                trustManagerFactory.init((KeyStore) null);
                sslContextBuilder.trustManager(trustManagerFactory);
            }
            sslContext = sslContextBuilder.build();
        } else {
            sslContext = null;
        }

        bootstrap = new Bootstrap();
        if (eventLoopGroup == null) {
            this.eventLoopGroup = new NioEventLoopGroup();
            bootstrap.group(this.eventLoopGroup);
        } else {
            this.eventLoopGroup = null;
            bootstrap.group(eventLoopGroup);
        }
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000)
                .channel(channelClass == null ? NioSocketChannel.class : channelClass).remoteAddress(host, port)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel c) throws Exception {
                        final HttpHeaders headers = new DefaultHttpHeaders();
                        headers.add(HttpHeaders.Names.AUTHORIZATION, token);
                        final WebSocketClientHandler handler = new WebSocketClientHandler(
                                WebSocketClientHandshakerFactory.newHandshaker(fullUri, WebSocketVersion.V13,
                                        null, false, headers));
                        final ChannelPipeline pipeline = c.pipeline();
                        if (sslContext != null) {
                            pipeline.addLast(sslContext.newHandler(c.alloc(), host, port));
                        }
                        pipeline.addLast(new ReadTimeoutHandler(30));
                        pipeline.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192));
                        pipeline.addLast(HANDLER_NAME, handler);

                        channel = c;
                    }
                });
    } catch (NoSuchAlgorithmException | SSLException | KeyStoreException e) {
        throw new RuntimeException(e);
    }
}

From source file:cn.npt.net.handler.BaseWebSocketClientHandler.java

License:Apache License

/**
 * //from   www.j  a v a  2s . com
 * @param uri eg ws://127.0.0.1:8080/websocket
 */
public BaseWebSocketClientHandler(URI uri) {
    this.handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false,
            new DefaultHttpHeaders());
}

From source file:cn.npt.net.websocket.WebSocketClient.java

License:Apache License

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 ? "192.168.20.71" : uri.getHost();
    final int port;
    if (uri.getPort() == -1) {
        if ("ws".equalsIgnoreCase(scheme)) {
            port = 80;//  w w w. ja v a 2  s .  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) {
        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 BaseWebSocketClientHandler handler = new EchoWebSocketClientHandler(
                WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false,
                        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), 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();
    }
}

From source file:com.athena.dolly.websocket.client.test.WebSocketClient.java

License:Apache License

private void initialize() throws InterruptedException {
    group = new NioEventLoopGroup();

    Bootstrap bootstrap = new Bootstrap();
    String protocol = uri.getScheme();
    if (!"ws".equals(protocol)) {
        throw new IllegalArgumentException("Unsupported protocol: " + protocol);
    }//w  ww.j av  a  2s . c  om

    HttpHeaders customHeaders = new DefaultHttpHeaders();
    customHeaders.add("MyHeader", "MyValue");

    // 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, false, customHeaders));

    bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("http-codec", new HttpClientCodec());
            pipeline.addLast("aggregator", new HttpObjectAggregator(8192));
            pipeline.addLast("ws-handler", handler);
        }
    });

    System.out.println("WebSocket Client connecting");
    ch = bootstrap.connect(uri.getHost(), uri.getPort()).sync().channel();
    handler.handshakeFuture().sync();

}

From source file:com.barchart.netty.client.transport.WebSocketTransport.java

License:BSD License

@Override
public void initPipeline(final ChannelPipeline pipeline) throws Exception {

    final WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri,
            WebSocketVersion.V13, null, false, null);

    final WebSocketClientProtocolHandler wsHandler = new WebSocketClientProtocolHandler(handshaker);

    pipeline.addFirst(new HttpClientCodec(), //
            new HttpObjectAggregator(65536), //
            wsHandler,/*from   w  w  w .j a v a2s  .c  o  m*/
            // Fires channelActive() after handshake and removes self
            new WebSocketConnectedNotifier(),
            // BinaryWebSocketFrame <-> ByteBuf codec before user codecs
            new WebSocketBinaryCodec());

    if (uri.getScheme().equalsIgnoreCase("wss") && pipeline.get(SslHandler.class) == null) {

        final SSLEngine sslEngine = SSLContext.getDefault().createSSLEngine();
        sslEngine.setUseClientMode(true);
        pipeline.addFirst("ssl", new SslHandler(sslEngine));

    }

}