io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory # newHandshaker ( ) 源码实例Demo

下面列出了 io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory # newHandshaker ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: arcusipcd   文件: IpcdClientDevice.java

private IpcdClientHandler createClientHandler(java.net.URI uri) {
	final IpcdClientHandler handler =
            new IpcdClientHandler(
                    WebSocketClientHandshakerFactory.newHandshaker(
                            uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders()), statusCallback);

    
    handler.setDownloadHandler(new DownloadHandler(this));
    handler.setFactoryResetHandler(new FactoryResetHandler(this));
    handler.setLeaveHandler(new LeaveHandler(this));
    handler.setRebootHandler(new RebootHandler(this));
    handler.setGetDeviceInfoHandler(new GetDeviceInfoHandler(this));
    handler.setGetEventConfigurationHandler(new GetEventConfigurationHandler(this));
    handler.setGetParameterInfoHandler(new GetParameterInfoHandler(this));
    handler.setGetParameterValuesHandler(new GetParameterValuesHandler(this));
    handler.setGetReportConfigurationHandler(new GetReportConfigurationHandler(this));
    handler.setSetDeviceInfoHandler(new SetDeviceInfoHandler(this));
    handler.setSetEventConfigurationHandler(new SetEventConfigurationHandler(this));
    handler.setSetParameterValuesHandler(new SetParameterValuesHandler(this));
    handler.setSetReportConfigurationHandler(new SetReportConfigurationHandler(this));
    
    return handler;
}
 

WebsocketClientOperations(URI currentURI,
		WebsocketClientSpec websocketClientSpec,
		HttpClientOperations replaced) {
	super(replaced);
	this.proxyPing = websocketClientSpec.handlePing();
	Channel channel = channel();
	onCloseState = MonoProcessor.create();

	String subprotocols = websocketClientSpec.protocols();
	handshaker = WebSocketClientHandshakerFactory.newHandshaker(currentURI,
				WebSocketVersion.V13,
				subprotocols != null && !subprotocols.isEmpty() ? subprotocols : null,
				true,
				replaced.requestHeaders()
				        .remove(HttpHeaderNames.HOST),
				websocketClientSpec.maxFramePayloadLength());

	handshaker.handshake(channel)
	          .addListener(f -> {
		          markPersistent(false);
		          channel.read();
	          });
}
 
源代码3 项目: 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, EmptyHttpHeaders.INSTANCE, 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);
}
 
源代码4 项目: Launcher   文件: ClientJSONPoint.java

public void open() throws Exception {
    //System.out.println("WebSocket Client connecting");
    webSocketClientHandler =
            new WebSocketClientHandler(
                    WebSocketClientHandshakerFactory.newHandshaker(
                            uri, WebSocketVersion.V13, null, false, EmptyHttpHeaders.INSTANCE, 12800000), this);
    ch = bootstrap.connect(uri.getHost(), port).sync().channel();
    webSocketClientHandler.handshakeFuture().sync();
}
 
源代码5 项目: Launcher   文件: ClientJSONPoint.java

public void openAsync(Runnable onConnect) {
    //System.out.println("WebSocket Client connecting");
    webSocketClientHandler =
            new WebSocketClientHandler(
                    WebSocketClientHandshakerFactory.newHandshaker(
                            uri, WebSocketVersion.V13, null, false, EmptyHttpHeaders.INSTANCE, 12800000), this);
    ChannelFuture future = bootstrap.connect(uri.getHost(), port);
    future.addListener((e) -> {
        ch = future.channel();
        webSocketClientHandler.handshakeFuture().addListener((e1) -> onConnect.run());
    });
}
 

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));
}
 
源代码7 项目: 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, EmptyHttpHeaders.INSTANCE, 65536));
        final MessageSerializer serializer = new GraphBinaryMessageSerializerV1();
        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);
    }
}
 

public WebSocketFrameTransport(final BrokerAdmin brokerAdmin)
{
    super(brokerAdmin, BrokerAdmin.PortType.ANONYMOUS_AMQPWS);
    URI uri = URI.create(String.format("tcp://%s:%d/",
                                       getBrokerAddress().getHostString(),
                                       getBrokerAddress().getPort()));
    _webSocketClientHandler = new WebSocketClientHandler(
            WebSocketClientHandshakerFactory.newHandshaker(
                    uri, WebSocketVersion.V13, "amqp", false, new DefaultHttpHeaders()));
}
 
源代码9 项目: 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.put(sessionId, TimelyPrincipal.anonymousPrincipal());
    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(HttpHeaderNames.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");
    }
}
 
源代码10 项目: qpid-jms   文件: NettyWsTransport.java

public NettyWebSocketTransportHandler() {
    DefaultHttpHeaders headers = new DefaultHttpHeaders();

    getTransportOptions().getHttpHeaders().forEach((key, value) -> {
        headers.set(key, value);
    });

    handshaker = WebSocketClientHandshakerFactory.newHandshaker(
        getRemoteLocation(), WebSocketVersion.V13, AMQP_SUB_PROTOCOL,
        true, headers, getMaxFrameSize());
}
 
源代码11 项目: blynk-server   文件: AppWebSocketClient.java

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()));
}
 

/**
 * @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;
}
 
源代码13 项目: dfactor   文件: DFSocketManager.java

@Override
		protected void initChannel(SocketChannel ch) throws Exception {
			final ChannelPipeline pipe = ch.pipeline();
			if(_sslCfg != null){ //ssl
				SslContext sslCtx = null;
				if(_isServer){
					sslCtx = SslContextBuilder.forServer(new File(_sslCfg.getCertPath()), 
							new File(_sslCfg.getPemPath())).build();
				}else{
					sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
				}
				SslHandler sslHandler = sslCtx.newHandler(ch.alloc());
				pipe.addLast(sslHandler);
			}
			//
			if(_decodeType == DFActorDefine.TCP_DECODE_WEBSOCKET){
				if(_isServer){
					pipe.addLast(new HttpServerCodec());
					pipe.addLast(new HttpObjectAggregator(_maxLen));
					pipe.addLast(new DFWSRequestHandler("/"+_wsSfx));
					pipe.addLast(new WebSocketServerProtocolHandler("/"+_wsSfx, null, true));
					if(_customHandler == null){
						pipe.addLast(new TcpWsHandler(_actorId, _requestId, _decodeType, (DFActorTcpDispatcher) _dispatcher, _decoder, _encoder));
					}else{
						pipe.addLast(_customHandler);
					}
				}else{
					pipe.addLast(new HttpClientCodec());
					pipe.addLast(new HttpObjectAggregator(_maxLen));
					if(_customHandler == null){
						DFWsClientHandler handler =  
			                    new DFWsClientHandler(  
			                            WebSocketClientHandshakerFactory.newHandshaker(  
			                            		new URI(_wsSfx), WebSocketVersion.V13, null, false, new DefaultHttpHeaders()),
			                            _actorId, _requestId, _decodeType, (DFActorTcpDispatcher) _dispatcher, _decoder, _encoder); 
						pipe.addLast(handler);
					}else{
						pipe.addLast(_customHandler);
					}
				}
			}
			else if(_decodeType == DFActorDefine.TCP_DECODE_HTTP){
				if(_isServer){
//					pipe.addLast(new HttpServerCodec());
					
					pipe.addLast(new HttpRequestDecoder());
					pipe.addLast(new HttpObjectAggregator(_maxLen));
					pipe.addLast(new HttpResponseEncoder());
					pipe.addLast(new ChunkedWriteHandler());
					
					if(_customHandler == null){
						pipe.addLast(new DFHttpSvrHandler(_actorId, _requestId, _decoder, (DFHttpDispatcher) _dispatcher, (CbHttpServer) _userHandler));
					}else{
						pipe.addLast(_customHandler);
					}
				}else{ //client
					pipe.addLast(new HttpClientCodec());
					pipe.addLast(new HttpObjectAggregator(_maxLen));
					if(_customHandler == null){
						pipe.addLast(new DFHttpCliHandler(_actorId, _requestId, _decoder, (DFHttpDispatcher) _dispatcher, 
								(CbHttpClient) _userHandler, (DFHttpCliReqWrap) _reqData));
					}else{
						pipe.addLast(_customHandler);
					}
				}
			}
			else{
				if(_decodeType == DFActorDefine.TCP_DECODE_LENGTH){ //length base field
					pipe.addLast(new LengthFieldBasedFrameDecoder(_maxLen, 0, 2, 0, 2));
				}
				if(_customHandler == null){
					pipe.addLast(new TcpHandler(_actorId, _requestId, _decodeType, (DFActorTcpDispatcher) _dispatcher, _decoder, _encoder));
				}else{
					pipe.addLast(_customHandler);
				}
			}
			
		}
 
源代码14 项目: arthas   文件: TunnelClient.java

public ChannelFuture connect(boolean reconnect) throws SSLException, URISyntaxException, InterruptedException {
    QueryStringEncoder queryEncoder = new QueryStringEncoder(this.tunnelServerUrl);
    queryEncoder.addParam("method", "agentRegister");
    if (id != null) {
        queryEncoder.addParam("id", id);
    }
    // ws://127.0.0.1:7777/ws?method=agentRegister
    final URI agentRegisterURI = queryEncoder.toUri();

    logger.info("Try to register arthas agent, uri: {}", agentRegisterURI);

    String scheme = agentRegisterURI.getScheme() == null ? "ws" : agentRegisterURI.getScheme();
    final String host = agentRegisterURI.getHost() == null ? "127.0.0.1" : agentRegisterURI.getHost();
    final int port;
    if (agentRegisterURI.getPort() == -1) {
        if ("ws".equalsIgnoreCase(scheme)) {
            port = 80;
        } else if ("wss".equalsIgnoreCase(scheme)) {
            port = 443;
        } else {
            port = -1;
        }
    } else {
        port = agentRegisterURI.getPort();
    }

    if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) {
        throw new IllegalArgumentException("Only WS(S) is supported. tunnelServerUrl: " + tunnelServerUrl);
    }

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

    WebSocketClientHandshaker newHandshaker = WebSocketClientHandshakerFactory.newHandshaker(agentRegisterURI,
            WebSocketVersion.V13, null, true, new DefaultHttpHeaders());
    final WebSocketClientProtocolHandler websocketClientHandler = new WebSocketClientProtocolHandler(newHandshaker);
    final TunnelClientSocketClientHandler handler = new TunnelClientSocketClientHandler(TunnelClient.this);

    Bootstrap bs = new Bootstrap();

    bs.group(eventLoopGroup).channel(NioSocketChannel.class).remoteAddress(host, port)
            .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), websocketClientHandler,
                            handler);
                }
            });

    ChannelFuture connectFuture = bs.connect();
    if (reconnect) {
        connectFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.cause() != null) {
                    logger.error("connect to tunnel server error, uri: {}", tunnelServerUrl, future.cause());
                }
            }
        });
    }
    channel = connectFuture.sync().channel();

    return handler.registerFuture();
}
 
源代码15 项目: arthas   文件: ForwardClient.java

public void start() throws URISyntaxException, SSLException, InterruptedException {
    String scheme = tunnelServerURI.getScheme() == null ? "ws" : tunnelServerURI.getScheme();
    final String host = tunnelServerURI.getHost() == null ? "127.0.0.1" : tunnelServerURI.getHost();
    final int port;
    if (tunnelServerURI.getPort() == -1) {
        if ("ws".equalsIgnoreCase(scheme)) {
            port = 80;
        } else if ("wss".equalsIgnoreCase(scheme)) {
            port = 443;
        } else {
            port = -1;
        }
    } else {
        port = tunnelServerURI.getPort();
    }

    if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) {
        logger.error("Only WS(S) is supported, uri: {}", tunnelServerURI);
        return;
    }

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

    // connect to local server
    WebSocketClientHandshaker newHandshaker = WebSocketClientHandshakerFactory.newHandshaker(tunnelServerURI,
            WebSocketVersion.V13, null, true, new DefaultHttpHeaders());
    final WebSocketClientProtocolHandler websocketClientHandler = new WebSocketClientProtocolHandler(newHandshaker);

    final ForwardClientSocketClientHandler forwardClientSocketClientHandler = new ForwardClientSocketClientHandler(
            localServerURI);

    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), websocketClientHandler,
                    forwardClientSocketClientHandler);
        }
    });

    channel = b.connect(tunnelServerURI.getHost(), port).sync().channel();
    logger.info("forward client connect to server success, uri: " + tunnelServerURI);
}
 

public PoloniexWSSClientRouter(URI url, Map<Double, IMessageHandler> subscriptions) throws URISyntaxException {
    this(WebSocketClientHandshakerFactory
            .newHandshaker(url, WebSocketVersion.V13, null, true, new DefaultHttpHeaders(), MAX_FRAME_LENGTH), subscriptions);
}
 
源代码17 项目: 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;
}
 

@FXML
public void connect() throws URISyntaxException {
	
	if( connected.get() ) {
		if( logger.isWarnEnabled() ) {
			logger.warn("client already connected; skipping connect");
		}
		return;  // already connected; should be prevented with disabled
	}
	
	String host = tfHost.getText();
	int port = Integer.parseInt(tfPort.getText());

	group = new NioEventLoopGroup();
	
	final WebSocketClientProtocolHandler handler =
			  new WebSocketClientProtocolHandler(
					  WebSocketClientHandshakerFactory.newHandshaker(
							  new URI("ws://" + host + "/ws"), WebSocketVersion.V13, null, false, new DefaultHttpHeaders()));
	  
	Task<Channel> task = new Task<Channel>() {

		@Override
		protected Channel call() throws Exception {
			
			updateMessage("Bootstrapping");
			updateProgress(0.1d, 1.0d);
			
			Bootstrap b = new Bootstrap();
			b
				.group(group)
				.channel(NioSocketChannel.class)
				.remoteAddress( new InetSocketAddress(host, port) )
				.handler( new ChannelInitializer<SocketChannel>() {
					@Override
					protected void initChannel(SocketChannel ch) throws Exception {
						ChannelPipeline p = ch.pipeline();
						p.addLast(new HttpClientCodec());
						p.addLast(new HttpObjectAggregator(8192));
						p.addLast(handler);
						p.addLast(new EchoClientHandlerWS(receivingMessageModel));
					}
				});
			
			updateMessage("Connecting");
			updateProgress(0.2d, 1.0d);

			ChannelFuture f = b.connect();				
			f.sync();
			Channel chn = f.channel();

			if( logger.isDebugEnabled() ) {
				logger.debug("[CONNECT] channel active=" + chn.isActive() + ", open=" + chn.isOpen() + ", register=" + chn.isRegistered() + ", writeable=" + chn.isWritable());
			}

			return chn;
		}

		@Override
		protected void succeeded() {
			
			channel = getValue();
			connected.set(true);
		}

		@Override
		protected void failed() {
			
			Throwable exc = getException();
			logger.error( "client connect error", exc );
			Alert alert = new Alert(AlertType.ERROR);
			alert.setTitle("Client");
			alert.setHeaderText( exc.getClass().getName() );
			alert.setContentText( exc.getMessage() );
			alert.showAndWait();
			
			connected.set(false);
		}
	};
	
	hboxStatus.visibleProperty().bind( task.runningProperty() );
	lblStatus.textProperty().bind( task.messageProperty() );
	piStatus.progressProperty().bind(task.progressProperty());
	
	new Thread(task).start();
}
 
源代码19 项目: 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;
    }
}
 
源代码20 项目: activemq-artemis   文件: NettyWSTransport.java

NettyWebSocketTransportHandler() {
   handshaker = WebSocketClientHandshakerFactory.newHandshaker(
      getRemoteLocation(), WebSocketVersion.V13, options.getWsSubProtocol(),
      true, new DefaultHttpHeaders(), getMaxFrameSize());
}