io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory Java Examples

The following examples show how to use io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: IpcdClientDevice.java    From arcusipcd with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #2
Source File: Channelizer.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #3
Source File: WebSocketClient.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
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()));
}
 
Example #4
Source File: WebsocketClientOperations.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
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();
	          });
}
 
Example #5
Source File: NettyWsTransport.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example #6
Source File: WebSocketClient.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #7
Source File: AppWebSocketClient.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
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()));
}
 
Example #8
Source File: BitsoWebSocket.java    From bitso-java with MIT License 5 votes vote down vote up
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);
}
 
Example #9
Source File: WebSocketIT.java    From timely with Apache License 2.0 5 votes vote down vote up
@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");
    }
}
 
Example #10
Source File: WebSocketFrameTransport.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
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()));
}
 
Example #11
Source File: WebSocketIT.java    From qonduit with Apache License 2.0 5 votes vote down vote up
@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(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");
    }
}
 
Example #12
Source File: WebSocketClientInitializer.java    From util4j with Apache License 2.0 5 votes vote down vote up
/**
 * 通道注册的时候配置websocket解码handler
 */
@Override
protected final void initChannel(Channel ch) throws Exception {
	ChannelPipeline pipeline=ch.pipeline();
	if (sslCtx != null) {
		pipeline.addLast(sslCtx.newHandler(ch.alloc(),host,port));
       }
	pipeline.addLast(new HttpClientCodec());
	pipeline.addLast(new ChunkedWriteHandler());
	pipeline.addLast(new HttpObjectAggregator(64*1024));
	pipeline.addLast(new WebSocketClientProtocolHandler(WebSocketClientHandshakerFactory.newHandshaker(webSocketURL, WebSocketVersion.V13, subprotocol, false, new DefaultHttpHeaders())));
       pipeline.addLast(new WebSocketConnectedClientHandler());//连接成功监听handler
}
 
Example #13
Source File: NettyWebSocketClient.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
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));
}
 
Example #14
Source File: ClientJSONPoint.java    From Launcher with GNU General Public License v3.0 5 votes vote down vote up
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());
    });
}
 
Example #15
Source File: ClientJSONPoint.java    From Launcher with GNU General Public License v3.0 5 votes vote down vote up
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();
}
 
Example #16
Source File: PoloniexWSSClientRouter.java    From poloniex-api-java with MIT License 4 votes vote down vote up
public PoloniexWSSClientRouter(URI url, Map<Double, IMessageHandler> subscriptions) throws URISyntaxException {
    this(WebSocketClientHandshakerFactory
            .newHandshaker(url, WebSocketVersion.V13, null, true, new DefaultHttpHeaders(), MAX_FRAME_LENGTH), subscriptions);
}
 
Example #17
Source File: WebSocketTestClient.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * @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;
}
 
Example #18
Source File: EchoClientControllerWS.java    From examples-javafx-repos1 with Apache License 2.0 4 votes vote down vote up
@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();
}
 
Example #19
Source File: ForwardClient.java    From arthas with Apache License 2.0 4 votes vote down vote up
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);
}
 
Example #20
Source File: WebSocketClient.java    From msf4j with Apache License 2.0 4 votes vote down vote up
/**
 * @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;
    }
}
 
Example #21
Source File: TunnelClient.java    From arthas with Apache License 2.0 4 votes vote down vote up
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();
}
 
Example #22
Source File: DFSocketManager.java    From dfactor with MIT License 4 votes vote down vote up
@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);
				}
			}
			
		}
 
Example #23
Source File: NettyWSTransport.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
NettyWebSocketTransportHandler() {
   handshaker = WebSocketClientHandshakerFactory.newHandshaker(
      getRemoteLocation(), WebSocketVersion.V13, options.getWsSubProtocol(),
      true, new DefaultHttpHeaders(), getMaxFrameSize());
}
 
Example #24
Source File: WebSocketTestClient.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
/**
 * @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;
}