Java 类io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory 实例源码

项目:util4j    文件:NettyTextWebSocketClient.java   
/**
     * 适配
     */
    @Override
    protected ChannelHandler fixHandlerBeforeConnect(final ChannelHandler handler) {
        ChannelHandler result=new ShareableChannelInboundHandler() {
            @Override
            public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
                Channel ch=ctx.channel();
                ch.pipeline().addLast(new HttpClientCodec());
                ch.pipeline().addLast(new HttpObjectAggregator(64*1024));
                ch.pipeline().addLast(new WebSocketClientProtocolHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())));
                ch.pipeline().addLast(new WebSocketConnectedClientHandler(handler));
                ctx.pipeline().remove(this);//移除当前handler
                ctx.pipeline().fireChannelRegistered();//重新从第一个handler抛出事件
            }
        };
//      ChannelInitializer<SocketChannel> result=new ChannelInitializer<SocketChannel>() {
//            @Override
//            protected void initChannel(SocketChannel ch) {
//              ch.pipeline().addLast(new HttpClientCodec());
//              ch.pipeline().addLast(new HttpObjectAggregator(64*1024));
//              ch.pipeline().addLast(new WebSocketClientProtocolHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())));
//              ch.pipeline().addLast(new WebSocketConnectedClientHandler(handler));
//            }
//        };
        return result;
    }
项目:util4j    文件:NettyBinaryWebSocketClient.java   
/**
     * 适配
     */
    @Override
    protected ChannelHandler fixHandlerBeforeConnect(final ChannelHandler handler) {
        ChannelHandler result=new ShareableChannelInboundHandler() {
            @Override
            public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
                Channel ch=ctx.channel();
                ch.pipeline().addLast(new HttpClientCodec());
                ch.pipeline().addLast(new HttpObjectAggregator(64*1024));
                ch.pipeline().addLast(new WebSocketClientProtocolHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())));
                ch.pipeline().addLast(new WebSocketConnectedClientHandler(handler));
                ctx.pipeline().remove(this);//移除当前handler
                ctx.fireChannelRegistered();//重新从第一个handler抛出事件
            }
        };
//      ChannelInitializer<SocketChannel> result=new ChannelInitializer<SocketChannel>() {
//            @Override
//            protected void initChannel(SocketChannel ch) {
//              ch.pipeline().addLast(new HttpClientCodec());
//              ch.pipeline().addLast(new HttpObjectAggregator(64*1024));
//              ch.pipeline().addLast(new WebSocketClientProtocolHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())));
//              ch.pipeline().addLast(new WebSocketConnectedClientHandler(handler));
//            }
//        };
        return result;
    }
项目:AudioConnect    文件:AudioConnectClient.java   
@Override
protected void initChannel(SocketChannel channel) throws SSLException {
    URI uri = config.getConnectionWebsocketUri();

    DefaultHttpHeaders headers = new DefaultHttpHeaders();
    headers.add(USER_ID_HEADER, config.getConnectionUserId().toString());
    headers.add(USER_PASSWORD_HEADER, config.getConnectionUserPassword());
    headers.add(SUPPLIER_ID_HEADER, config.getConnectionServerId());

    WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri, WS_VERSION, null, false, headers);

    ChannelPipeline pipeline = channel.pipeline();
    if (config.isConnectionSecure()) {
        try {
            SslContext sslContext = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
            pipeline.addLast(sslContext.newHandler(channel.alloc()));
        } catch (SSLException e) {
            logger.log(Level.SEVERE, "Shutting down client due to unexpected failure to create SSL context", e);
            throw e;
        }
    }
    pipeline.addLast(new HttpClientCodec());
    pipeline.addLast(new HttpObjectAggregator(8192));
    pipeline.addLast(new AudioConnectClientHandler(handshaker));
}
项目:LiteGraph    文件:Channelizer.java   
@Override
public void configure(final ChannelPipeline pipeline) {
    final String scheme = connection.getUri().getScheme();
    if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme))
        throw new IllegalStateException("Unsupported scheme (only ws: or wss: supported): " + scheme);

    if (!supportsSsl() && "wss".equalsIgnoreCase(scheme))
        throw new IllegalStateException("To use wss scheme ensure that enableSsl is set to true in configuration");

    final int maxContentLength = cluster.connectionPoolSettings().maxContentLength;
    handler = new WebSocketClientHandler(
            WebSocketClientHandshakerFactory.newHandshaker(
                    connection.getUri(), WebSocketVersion.V13, null, false, HttpHeaders.EMPTY_HEADERS, maxContentLength));

    pipeline.addLast("http-codec", new HttpClientCodec());
    pipeline.addLast("aggregator", new HttpObjectAggregator(maxContentLength));
    pipeline.addLast("ws-handler", handler);
    pipeline.addLast("gremlin-encoder", webSocketGremlinRequestEncoder);
    pipeline.addLast("gremlin-decoder", webSocketGremlinResponseDecoder);
}
项目:blynk-server    文件:WebSocketClient.java   
public WebSocketClient(String host, int port, String path, boolean isSSL) throws Exception {
    super(host, port, new Random());

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

    if (isSSL) {
        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()));
}
项目:tinkerpop    文件:Channelizer.java   
@Override
public void configure(final ChannelPipeline pipeline) {
    final String scheme = connection.getUri().getScheme();
    if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme))
        throw new IllegalStateException("Unsupported scheme (only ws: or wss: supported): " + scheme);

    if (!supportsSsl() && "wss".equalsIgnoreCase(scheme))
        throw new IllegalStateException("To use wss scheme ensure that enableSsl is set to true in configuration");

    final int maxContentLength = cluster.connectionPoolSettings().maxContentLength;
    handler = new WebSocketClientHandler(
            WebSocketClientHandshakerFactory.newHandshaker(
                    connection.getUri(), WebSocketVersion.V13, null, false, HttpHeaders.EMPTY_HEADERS, maxContentLength));

    pipeline.addLast("http-codec", new HttpClientCodec());
    pipeline.addLast("aggregator", new HttpObjectAggregator(maxContentLength));
    pipeline.addLast("ws-handler", handler);
    pipeline.addLast("gremlin-encoder", webSocketGremlinRequestEncoder);
    pipeline.addLast("gremlin-decoder", webSocketGremlinResponseDecoder);
}
项目:firebase-admin-java    文件:NettyWebSocketClient.java   
WebSocketClientHandler(
    URI uri, String userAgent, WebsocketConnection.WSClientEventHandler delegate) {
  this.delegate = checkNotNull(delegate, "delegate must not be null");
  checkArgument(!Strings.isNullOrEmpty(userAgent), "user agent must not be null or empty");
  this.handshaker = WebSocketClientHandshakerFactory.newHandshaker(
      uri, WebSocketVersion.V13, null, true,
      new DefaultHttpHeaders().add("User-Agent", userAgent));
}
项目:util4j    文件:WebSocketClientInitializer.java   
/**
 * 通道注册的时候配置websocket解码handler
 */
@Override
protected final void initChannel(Channel ch) throws Exception {
    ChannelPipeline pipeline=ch.pipeline();
    pipeline.addLast(new HttpClientCodec());
    pipeline.addLast(new ChunkedWriteHandler());
    pipeline.addLast(new HttpObjectAggregator(64*1024));
    pipeline.addLast(new WebSocketClientProtocolHandler(WebSocketClientHandshakerFactory.newHandshaker(new URI(url), WebSocketVersion.V13, null, false, new DefaultHttpHeaders())));
       pipeline.addLast(new WebSocketConnectedClientHandler());//连接成功监听handler
}
项目:qonduit    文件:WebSocketIT.java   
@Before
public void setup() throws Exception {
    s = new Server(conf);
    s.run();

    Connector con = mac.getConnector("root", "secret");
    con.securityOperations().changeUserAuthorizations("root", new Authorizations("A", "B", "C", "D", "E", "F"));

    this.sessionId = UUID.randomUUID().toString();
    AuthCache.getCache().put(sessionId, token);
    group = new NioEventLoopGroup();
    SslContext ssl = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();

    String cookieVal = ClientCookieEncoder.STRICT.encode(Constants.COOKIE_NAME, sessionId);
    HttpHeaders headers = new DefaultHttpHeaders();
    headers.add(Names.COOKIE, cookieVal);

    WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(LOCATION,
            WebSocketVersion.V13, (String) null, false, headers);
    handler = new ClientHandler(handshaker);
    Bootstrap boot = new Bootstrap();
    boot.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("ssl", ssl.newHandler(ch.alloc(), "127.0.0.1", WS_PORT));
            ch.pipeline().addLast(new HttpClientCodec());
            ch.pipeline().addLast(new HttpObjectAggregator(8192));
            ch.pipeline().addLast(handler);
        }
    });
    ch = boot.connect("127.0.0.1", WS_PORT).sync().channel();
    // Wait until handshake is complete
    while (!handshaker.isHandshakeComplete()) {
        sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
        LOG.debug("Waiting for Handshake to complete");
    }
}
项目:timely    文件:WebSocketIT.java   
@Before
public void setup() throws Exception {
    s = new Server(conf);
    s.run();

    Connector con = mac.getConnector("root", "secret");
    con.securityOperations().changeUserAuthorizations("root", new Authorizations("A", "B", "C", "D", "E", "F"));

    this.sessionId = UUID.randomUUID().toString();
    AuthCache.getCache().put(sessionId, token);
    group = new NioEventLoopGroup();
    SslContext ssl = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();

    String cookieVal = ClientCookieEncoder.STRICT.encode(Constants.COOKIE_NAME, sessionId);
    HttpHeaders headers = new DefaultHttpHeaders();
    headers.add(Names.COOKIE, cookieVal);

    WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(LOCATION,
            WebSocketVersion.V13, (String) null, false, headers);
    handler = new ClientHandler(handshaker);
    Bootstrap boot = new Bootstrap();
    boot.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("ssl", ssl.newHandler(ch.alloc(), "127.0.0.1", WS_PORT));
            ch.pipeline().addLast(new HttpClientCodec());
            ch.pipeline().addLast(new HttpObjectAggregator(8192));
            ch.pipeline().addLast(handler);
        }
    });
    ch = boot.connect("127.0.0.1", WS_PORT).sync().channel();
    // Wait until handshake is complete
    while (!handshaker.isHandshakeComplete()) {
        sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
        LOG.debug("Waiting for Handshake to complete");
    }
}
项目:LiteGraph    文件:WebSocketClient.java   
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 {
        final WebSocketClientHandler wsHandler =
                new WebSocketClientHandler(
                        WebSocketClientHandshakerFactory.newHandshaker(
                                uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders()));
        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(8192),
                                wsHandler,
                                new WebSocketGremlinRequestEncoder(true, serializer),
                                new WebSocketGremlinResponseDecoder(serializer),
                                callbackResponseHandler);
                    }
                });

        channel = b.connect(uri.getHost(), uri.getPort()).sync().channel();
        wsHandler.handshakeFuture().sync();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
项目:bitso-java    文件:BitsoWebSocket.java   
public void openConnection() throws InterruptedException{
    Bootstrap bootstrap = new Bootstrap();

    final WebSocketClientHandler handler =
            new WebSocketClientHandler(
                    WebSocketClientHandshakerFactory.newHandshaker(
                            mUri, WebSocketVersion.V08, null, false,
                            new DefaultHttpHeaders()));

    bootstrap.group(mGroup)
    .channel(NioSocketChannel.class)
    .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel socketChannel){
                    ChannelPipeline channelPipeline =
                            socketChannel.pipeline();
                    channelPipeline.addLast(mSslContext.newHandler(
                            socketChannel.alloc(),
                            mUri.getHost(),
                            PORT));
                    channelPipeline.addLast(new HttpClientCodec(),
                            new HttpObjectAggregator(8192),
                            handler);
                }
            });

    mChannel = bootstrap.connect(mUri.getHost(), PORT).sync().channel();
    handler.handshakeFuture().sync();
    setConnected(Boolean.TRUE);
}
项目:gameboot    文件:WebSocketHandler.java   
/**
 * Inits the.
 *
 * @throws URISyntaxException
 *           the URI syntax exception
 */
public void init() throws URISyntaxException {
  handshaker = WebSocketClientHandshakerFactory.newHandshaker(createUri(),
      WebSocketVersion.V13,
      null,
      false,
      customHeaders);
}
项目:tinkerpop    文件:WebSocketClient.java   
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 {
        final WebSocketClientHandler wsHandler =
                new WebSocketClientHandler(
                        WebSocketClientHandshakerFactory.newHandshaker(
                                uri, WebSocketVersion.V13, null, false, HttpHeaders.EMPTY_HEADERS, 65536));
        final MessageSerializer serializer = new GryoMessageSerializerV3d0();
        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);
    }
}
项目:Blaubot    文件:WebsocketClientHandler.java   
/**
 * Creates a new WebSocketClientHandler that manages the BlaubotWebsocketConnection
 * @param uri                  The uri to connect with
 * @param remoteUniqueDeviceId the unique device id of the device we are connecting to
 * @param listenerReference    a reference Object that handles the connection listener
 */
public WebsocketClientHandler(URI uri, String remoteUniqueDeviceId, AtomicReference<IBlaubotIncomingConnectionListener> listenerReference) {
    // Connect with V13 (RFC 6455 aka HyBi-17).
    // other options are V08 or V00.
    // If V00 is used, ping is not supported and remember to change
    // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
    this.handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders(), BlaubotWebsocketAdapter.MAX_WEBSOCKET_FRAME_SIZE);
    this.remoteDeviceUniqueDeviceId = remoteUniqueDeviceId;
    this.incomingConnectionListenerReference = listenerReference;
}
项目:divconq    文件:ClientHandler.java   
public ClientHandler(SocketInfo info) {
    super(info, false);

    HttpHeaders customHeaders = new DefaultHttpHeaders();
    customHeaders.add("x-DivConq-Layer", "dcPrivate");

    this.handshaker = WebSocketClientHandshakerFactory.newHandshaker(info.getUri(), WebSocketVersion.V13, null, false, customHeaders);
}
项目:top-traffic    文件:WebSocketConnection.java   
@Override
protected void preparePipeline(ChannelPipeline pipeline) {
    pipeline.addLast(
            new HttpClientCodec(),
            new HttpObjectAggregator(8192));
    pipeline.addLast("handler",
            new WebSocketClientHandler(this,
                    WebSocketClientHandshakerFactory.newHandshaker(
                            this.uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())));
}
项目:wecard-server    文件:WebSocketClient.java   
public void run() 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.
            this.handler = new WebSocketClientHandler(uid,
                    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)
                            );
//
//                            p.addLast("frameDecoder", new ProtobufVarint32FrameDecoder());
//                            p.addLast("protobufDecoder", new ProtobufDecoder(Response.HeshResMessage.getDefaultInstance()));
//
//                            p.addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender());
//                            p.addLast("protobufEncoder", new ProtobufEncoder());

                            p.addLast(handler);

                        }
                    });

            this.channel = b.connect(uri.getHost(), port).sync().channel();
//            handler.handshakeFuture().sync();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//            group.shutdownGracefully();
        }
    }
项目:SurvivalMMO    文件:WebSocketClientHandler.java   
public WebSocketClientHandler(URI uri) {
    handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri,
            WebSocketVersion.V13, null, false, new DefaultHttpHeaders());
}
项目:SlackDiscordBridge    文件:WebSocketHandler.java   
public WebSocketHandler(final AbstractWebSocketConnection webSocketConnection)
{
    this.webSocketConnection = webSocketConnection;
    this.handshaker = WebSocketClientHandshakerFactory.newHandshaker(webSocketConnection.getUri(), WebSocketVersion.V13, null, false, new DefaultHttpHeaders());
}
项目:product-ei    文件:WebSocketTestClient.java   
/**
 * @return true if the handshake is done properly.
 * @throws URISyntaxException   throws if there is an error in the URI syntax.
 * @throws InterruptedException throws if the connecting the server is interrupted.
 */
public boolean handhshake() throws InterruptedException, URISyntaxException, SSLException, ProtocolException {
    boolean isSuccess;
    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)) {
        logger.error("Only WS(S) is supported.");
        return false;
    }

    final boolean ssl = "wss".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    group = new NioEventLoopGroup();

    HttpHeaders headers = new DefaultHttpHeaders();
    for (Map.Entry<String, String> entry : customHeaders.entrySet()) {
        headers.add(entry.getKey(), entry.getValue());
    }
    // 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.
    handler = new WebSocketClientHandler(
            WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, subProtocol, true, headers),
            latch);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.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 = bootstrap.connect(uri.getHost(), port).sync().channel();
    isSuccess = handler.handshakeFuture().sync().isSuccess();
    logger.info("WebSocket Handshake successful : " + isSuccess);
    return isSuccess;
}
项目:xockets.io    文件:AbstractClient.java   
@Override
public void connect() throws InterruptedException{
    // 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.
    handler =
            new WebSocketClientHandler(
                    WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders(),this.getMaxPayload()));


    //make sure the handler has a refernce to this object.
    handler.setClient(this);

    Bootstrap clientBoot = new Bootstrap();
    clientBoot.group(group)
    .channel(NioSocketChannel.class)
    .handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) {
            ChannelPipeline p = ch.pipeline();
            SSLEngine sslEngine=null;
            if(AbstractClient.this.isEncrypted()){
                if(sslContext == null){
                    sslEngine = new SSLFactory().createClientSslCtx(Config.getInstance()).newEngine(ch.alloc(), uri.getHost(),uri.getPort());
                }else{
                    sslEngine = sslContext.newEngine(ch.alloc(),uri.getHost(),uri.getPort());
                }

                sslEngine.setEnabledProtocols(Const.TLS_PROTOCOLS);
                sslEngine.setUseClientMode(true);
                p.addLast(new SslHandler(sslEngine));
            }

            p.addLast( new HttpClientCodec());
            p.addLast(new HttpObjectAggregator(8192));
            if(AbstractClient.this.isCompress()){
                p.addLast(WebSocketClientCompressionHandler.INSTANCE);
            }
            p.addLast(handler);


        }
    });


    this.ch = clientBoot.connect(uri.getHost(), uri.getPort()).sync().channel();
    handler.handshakeFuture().sync();   

}
项目:msf4j    文件:WebSocketClient.java   
/**
 * @return true if the handshake is done properly.
 * @throws URISyntaxException throws if there is an error in the URI syntax.
 * @throws InterruptedException throws if the connecting the server is interrupted.
 */
public boolean handhshake() throws InterruptedException, URISyntaxException, SSLException {
    boolean isDone;
    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)) {
        logger.error("Only WS(S) is supported.");
        return false;
    }

    final boolean ssl = "wss".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContextBuilder.forClient()
                                  .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    group = new NioEventLoopGroup();

    HttpHeaders headers = new DefaultHttpHeaders();
    customHeaders.entrySet().forEach(
            header -> headers.add(header.getKey(), header.getValue())
    );
    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.
        handler =
                new WebSocketClientHandler(
                        WebSocketClientHandshakerFactory.newHandshaker(
                                uri, WebSocketVersion.V13, subProtocol,
                                true, headers));

        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 = b.connect(uri.getHost(), port).sync().channel();
        isDone = handler.handshakeFuture().sync().isSuccess();
        logger.debug("WebSocket Handshake successful : " + isDone);
        return isDone;
    } catch (Exception e) {
        logger.error("Handshake unsuccessful : " + e.getMessage(), e);
        return false;
    }
}
项目:dslink-java-android    文件:AndroidWsProvider.java   
@Override
public void connect(WsClient client) {
    if (client == null) {
        throw new NullPointerException("client");
    }
    final URLInfo url = client.getUrl();
    String full = url.protocol + "://" + url.host
            + ":" + url.port + url.path;
    URI uri;
    try {
        uri = new URI(full);
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
    WebSocketVersion v = WebSocketVersion.V13;
    HttpHeaders h = new DefaultHttpHeaders();
    final WebSocketClientHandshaker wsch = WebSocketClientHandshakerFactory
            .newHandshaker(uri, v, null, true, h, Integer.MAX_VALUE);
    final WebSocketHandler handler = new WebSocketHandler(wsch, client);

    Bootstrap b = new Bootstrap();
    b.group(SharedObjects.getLoop());
    b.channel(NioSocketChannel.class);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            if (url.secure) {
                TrustManagerFactory man = InsecureTrustManagerFactory.INSTANCE;
                SslContext con = SslContext.newClientContext(man);
                p.addLast(con.newHandler(ch.alloc()));
            }

            p.addLast(new HttpClientCodec());
            p.addLast(new HttpObjectAggregator(8192));
            p.addLast(handler);
        }
    });

    ChannelFuture fut = b.connect(url.host, url.port);
    fut.syncUninterruptibly();
    handler.handshakeFuture().syncUninterruptibly();
}
项目:idea-websocket-client    文件:WebSocketClient.java   
@Override
public void connect(String url) throws Exception {
  URI uri = new URI(url);
  setConnected(false);

  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;
    } else if ("https".equalsIgnoreCase(scheme)) {
      port = 443;
    } else {
      port = -1;
    }
  } else {
    port = uri.getPort();
  }

  if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) {
    Notifications.Bus.notify(
        new Notification(
            "Websocket Client",
            "Unable to connect",
            "Only WS(S) is supported.",
            NotificationType.ERROR)
    );
    return;
  }

  EventLoopGroup group = new NioEventLoopGroup();
  try {
    WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(
        uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders());
    WebSocketClientHandler webSocketClientHandler = new WebSocketClientHandler(handshaker);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group)
        .channel(NioSocketChannel.class)
        .handler(new ChannelInitializer<SocketChannel>() {
          @Override
          protected void initChannel(SocketChannel ch) {
            ChannelPipeline p = ch.pipeline();

            p.addLast(
                new HttpClientCodec(),
                new HttpObjectAggregator(8192),
                webSocketClientHandler);
          }
        });

    channel = bootstrap.connect(uri.getHost(), port).sync().channel();
    webSocketClientHandler.handshakeFuture().sync();
    setConnected(true);

    for (; ; );
  } finally {
    group.shutdownGracefully();
    setConnected(false);
  }
}
项目:carbon-transports    文件:WebSocketTestClient.java   
/**
 * @return true if the handshake is done properly.
 * @throws URISyntaxException throws if there is an error in the URI syntax.
 * @throws InterruptedException throws if the connecting the server is interrupted.
 */
public boolean handhshake() throws InterruptedException, URISyntaxException, SSLException, ProtocolException {
    boolean isSuccess;
    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)) {
        logger.error("Only WS(S) is supported.");
        return false;
    }

    final boolean ssl = "wss".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContextBuilder.forClient()
                .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    group = new NioEventLoopGroup();

    HttpHeaders headers = new DefaultHttpHeaders();
    customHeaders.entrySet().forEach(
            header -> headers.add(header.getKey(), header.getValue())
    );
    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.
        handler =
                new WebSocketClientHandler(
                        WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, subProtocol,
                                                                       true, headers), latch);

        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 = b.connect(uri.getHost(), port).sync().channel();
        isSuccess = handler.handshakeFuture().sync().isSuccess();
        logger.debug("WebSocket Handshake successful : " + isSuccess);
        return isSuccess;
    } catch (Exception e) {
        logger.error("Handshake unsuccessful : " + e.getMessage());
        throw new ProtocolException("Protocol exception: " + e.getMessage());
    }
}
项目:activemq-artemis    文件:NettyWSTransport.java   
NettyWebSocketTransportHandler() {
   handshaker = WebSocketClientHandshakerFactory.newHandshaker(
      getRemoteLocation(), WebSocketVersion.V13, options.getWsSubProtocol(),
      true, new DefaultHttpHeaders(), getMaxFrameSize());
}
项目:dslink-java-android    文件:AndroidWsProvider.java   
@Override
public void connect(WsClient client) {
    if (client == null) {
        throw new NullPointerException("client");
    }
    final URLInfo url = client.getUrl();
    String full = url.protocol + "://" + url.host
            + ":" + url.port + url.path;
    URI uri;
    try {
        uri = new URI(full);
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
    WebSocketVersion v = WebSocketVersion.V13;
    HttpHeaders h = new DefaultHttpHeaders();
    final WebSocketClientHandshaker wsch = WebSocketClientHandshakerFactory
            .newHandshaker(uri, v, null, true, h, Integer.MAX_VALUE);
    final WebSocketHandler handler = new WebSocketHandler(wsch, client);

    Bootstrap b = new Bootstrap();
    b.group(SharedObjects.getLoop());
    b.channel(NioSocketChannel.class);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            if (url.secure) {
                TrustManagerFactory man = InsecureTrustManagerFactory.INSTANCE;
                SslContext con = SslContext.newClientContext(man);
                p.addLast(con.newHandler(ch.alloc()));
            }

            p.addLast(new HttpClientCodec());
            p.addLast(new HttpObjectAggregator(8192));
            p.addLast(handler);
        }
    });

    ChannelFuture fut = b.connect(url.host, url.port);
    fut.syncUninterruptibly();
    handler.handshakeFuture().syncUninterruptibly();
}
项目:qpid-jms    文件:NettyWsTransport.java   
public NettyWebSocketTransportHandler() {
    handshaker = WebSocketClientHandshakerFactory.newHandshaker(
        getRemoteLocation(), WebSocketVersion.V13, AMQP_SUB_PROTOCOL,
        true, new DefaultHttpHeaders(), getMaxFrameSize());
}