List of usage examples for io.netty.handler.ssl SslHandler SslHandler
public SslHandler(SSLEngine engine)
From source file:reactor.io.net.impl.netty.tcp.NettyTcpClient.java
License:Apache License
protected void addSecureHandler(SocketChannel ch) throws Exception { SSLEngine ssl = new SSLEngineSupplier(getSslOptions(), true).get(); if (log.isDebugEnabled()) { log.debug("SSL enabled using keystore {}", (null != getSslOptions() && null != getSslOptions().keystoreFile() ? getSslOptions().keystoreFile() : "<DEFAULT>")); }/* w w w .j av a2s.c o m*/ ch.pipeline().addLast(new SslHandler(ssl)); }
From source file:reactor.io.net.impl.netty.tcp.NettyTcpServer.java
License:Apache License
@Override protected Promise<Void> doStart(final ReactorChannelHandler<IN, OUT, ChannelStream<IN, OUT>> handler) { bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override//from w w w.j av a 2s .c o m public void initChannel(final SocketChannel ch) throws Exception { if (nettyOptions != null) { SocketChannelConfig config = ch.config(); config.setReceiveBufferSize(nettyOptions.rcvbuf()); config.setSendBufferSize(nettyOptions.sndbuf()); config.setKeepAlive(nettyOptions.keepAlive()); config.setReuseAddress(nettyOptions.reuseAddr()); config.setSoLinger(nettyOptions.linger()); config.setTcpNoDelay(nettyOptions.tcpNoDelay()); } if (log.isDebugEnabled()) { log.debug("CONNECT {}", ch); } if (null != getSslOptions()) { SSLEngine ssl = new SSLEngineSupplier(getSslOptions(), false).get(); if (log.isDebugEnabled()) { log.debug("SSL enabled using keystore {}", (null != getSslOptions().keystoreFile() ? getSslOptions().keystoreFile() : "<DEFAULT>")); } ch.pipeline().addLast(new SslHandler(ssl)); } if (null != nettyOptions && null != nettyOptions.pipelineConfigurer()) { nettyOptions.pipelineConfigurer().accept(ch.pipeline()); } bindChannel(handler, ch); } }); ChannelFuture bindFuture = bootstrap.bind(); final Promise<Void> promise = Promises.prepare(); bindFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { log.info("BIND {}", future.channel().localAddress()); if (future.isSuccess()) { if (listenAddress.getPort() == 0) { listenAddress = (InetSocketAddress) future.channel().localAddress(); } promise.onComplete(); } else { promise.onError(future.cause()); } } }); return promise; }
From source file:reactor.io.net.netty.tcp.NettyTcpClient.java
License:Apache License
/** * Creates a new NettyTcpClient that will use the given {@code env} for configuration and the given {@code * reactor} to//from ww w .j a v a2 s. c o m * send events. The number of IO threads used by the client is configured by the environment's {@code * reactor.tcp.ioThreadCount} property. In its absence the number of IO threads will be equal to the {@link * Environment#PROCESSORS number of available processors}. </p> The client will connect to the given {@code * connectAddress}, configuring its socket using the given {@code opts}. The given {@code codec} will be used for * encoding and decoding of data. * * @param env The configuration environment * @param reactor The reactor used to send events * @param connectAddress The address the client will connect to * @param options The configuration options for the client's socket * @param sslOptions The SSL configuration options for the client's socket * @param codec The codec used to encode and decode data * @param consumers The consumers that will interact with the connection */ public NettyTcpClient(@Nonnull Environment env, @Nonnull EventBus reactor, @Nonnull InetSocketAddress connectAddress, @Nonnull final ClientSocketOptions options, @Nullable final SslOptions sslOptions, @Nullable Codec<Buffer, IN, OUT> codec, @Nonnull Collection<Consumer<NetChannel<IN, OUT>>> consumers) { super(env, reactor, connectAddress, options, sslOptions, codec, consumers); this.connectAddress = connectAddress; if (options instanceof NettyClientSocketOptions) { this.nettyOptions = (NettyClientSocketOptions) options; } else { this.nettyOptions = null; } if (null != nettyOptions && null != nettyOptions.eventLoopGroup()) { this.ioGroup = nettyOptions.eventLoopGroup(); } else { int ioThreadCount = env.getProperty("reactor.tcp.ioThreadCount", Integer.class, Environment.PROCESSORS); this.ioGroup = new NioEventLoopGroup(ioThreadCount, new NamedDaemonThreadFactory("reactor-tcp-io")); } this.bootstrap = new Bootstrap().group(ioGroup).channel(NioSocketChannel.class) .option(ChannelOption.SO_RCVBUF, options.rcvbuf()).option(ChannelOption.SO_SNDBUF, options.sndbuf()) .option(ChannelOption.SO_KEEPALIVE, options.keepAlive()) .option(ChannelOption.SO_LINGER, options.linger()) .option(ChannelOption.TCP_NODELAY, options.tcpNoDelay()).remoteAddress(this.connectAddress) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(final SocketChannel ch) throws Exception { ch.config().setConnectTimeoutMillis(options.timeout()); if (null != sslOptions) { SSLEngine ssl = new SSLEngineSupplier(sslOptions, true).get(); if (log.isDebugEnabled()) { log.debug("SSL enabled using keystore {}", (null != sslOptions.keystoreFile() ? sslOptions.keystoreFile() : "<DEFAULT>")); } ch.pipeline().addLast(new SslHandler(ssl)); } if (null != nettyOptions && null != nettyOptions.pipelineConfigurer()) { nettyOptions.pipelineConfigurer().accept(ch.pipeline()); } ch.pipeline().addLast(createChannelHandlers(ch)); } }); this.connectionSupplier = new Supplier<ChannelFuture>() { @Override public ChannelFuture get() { if (!closing) { return bootstrap.connect(getConnectAddress()); } else { return null; } } }; }
From source file:reactor.io.net.netty.tcp.NettyTcpServer.java
License:Apache License
protected NettyTcpServer(@Nonnull Environment env, @Nonnull EventBus reactor, @Nullable InetSocketAddress listenAddress, final ServerSocketOptions options, final SslOptions sslOptions, @Nullable Codec<Buffer, IN, OUT> codec, @Nonnull Collection<Consumer<NetChannel<IN, OUT>>> consumers) { super(env, reactor, listenAddress, options, sslOptions, codec, consumers); if (options instanceof NettyServerSocketOptions) { this.nettyOptions = (NettyServerSocketOptions) options; } else {//from www . j a va2 s.c o m this.nettyOptions = null; } int selectThreadCount = env.getProperty("reactor.tcp.selectThreadCount", Integer.class, Environment.PROCESSORS / 2); int ioThreadCount = env.getProperty("reactor.tcp.ioThreadCount", Integer.class, Environment.PROCESSORS); this.selectorGroup = new NioEventLoopGroup(selectThreadCount, new NamedDaemonThreadFactory("reactor-tcp-select")); if (null != nettyOptions && null != nettyOptions.eventLoopGroup()) { this.ioGroup = nettyOptions.eventLoopGroup(); } else { this.ioGroup = new NioEventLoopGroup(ioThreadCount, new NamedDaemonThreadFactory("reactor-tcp-io")); } this.bootstrap = new ServerBootstrap().group(selectorGroup, ioGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, options.backlog()) .option(ChannelOption.SO_RCVBUF, options.rcvbuf()).option(ChannelOption.SO_SNDBUF, options.sndbuf()) .option(ChannelOption.SO_REUSEADDR, options.reuseAddr()) .localAddress((null == listenAddress ? new InetSocketAddress(3000) : listenAddress)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(final SocketChannel ch) throws Exception { SocketChannelConfig config = ch.config(); config.setReceiveBufferSize(options.rcvbuf()); config.setSendBufferSize(options.sndbuf()); config.setKeepAlive(options.keepAlive()); config.setReuseAddress(options.reuseAddr()); config.setSoLinger(options.linger()); config.setTcpNoDelay(options.tcpNoDelay()); if (log.isDebugEnabled()) { log.debug("CONNECT {}", ch); } if (null != sslOptions) { SSLEngine ssl = new SSLEngineSupplier(sslOptions, false).get(); if (log.isDebugEnabled()) { log.debug("SSL enabled using keystore {}", (null != sslOptions.keystoreFile() ? sslOptions.keystoreFile() : "<DEFAULT>")); } ch.pipeline().addLast(new SslHandler(ssl)); } if (null != nettyOptions && null != nettyOptions.pipelineConfigurer()) { nettyOptions.pipelineConfigurer().accept(ch.pipeline()); } ch.pipeline().addLast(createChannelHandlers(ch)); ch.closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (log.isDebugEnabled()) { log.debug("CLOSE {}", ch); } close(ch); } }); } }); }
From source file:us.aaronweiss.juicebot.Bot.java
License:Open Source License
/** * Constructs a new {@code Bot}./*w ww . j a v a 2 s . co m*/ * * @param username the username of the bot * @param simple whether or not the bot should use the simple messaging API * @param useSSL whether or not the bot should use SSL */ public Bot(String username, boolean simple, final boolean useSSL) { this.username = username; this.simple = simple; bootstrap = new Bootstrap(); bootstrap.group(new OioEventLoopGroup()); bootstrap.channel(OioSocketChannel.class); bootstrap.handler(new ChannelInitializer<OioSocketChannel>() { @Override protected void initChannel(OioSocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); // SSL Support if (useSSL) { SSLEngine engine = SSLContext.getDefault().createSSLEngine(); engine.setUseClientMode(true); pipeline.addLast("ssl", new SslHandler(engine)); } // Decoders pipeline.addLast("frameDecoder", new LineBasedFrameDecoder(1000)); pipeline.addLast("stringDecoder", new StringDecoder(CharsetUtil.UTF_8)); // Encoder pipeline.addLast("stringEncoder", new StringEncoder(CharsetUtil.UTF_8)); // Handlers pipeline.addLast("botHandler", new ClientHandlerAdapter(Bot.this)); } }); bootstrap.option(ChannelOption.TCP_NODELAY, true); }
From source file:whitespell.net.websockets.socketio.SocketIOChannelInitializer.java
License:Apache License
@Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); boolean isFlashTransport = configuration.getTransports().contains(FlashSocketTransport.NAME); if (isFlashTransport) { pipeline.addLast(FLASH_POLICY_HANDLER, flashPolicyHandler); }/* w ww .j ava 2s . c o m*/ if (sslContext != null) { SSLEngine engine = sslContext.createSSLEngine(); engine.setUseClientMode(false); pipeline.addLast(SSL_HANDLER, new SslHandler(engine)); } pipeline.addLast(HTTP_REQUEST_DECODER, new HttpRequestDecoder()); pipeline.addLast(HTTP_AGGREGATOR, new HttpObjectAggregator(configuration.getMaxHttpContentLength())); pipeline.addLast(HTTP_ENCODER, new HttpResponseEncoder()); if (isFlashTransport) { pipeline.addLast(RESOURCE_HANDLER, resourceHandler); } pipeline.addLast(PACKET_HANDLER, packetHandler); pipeline.addLast(AUTHORIZE_HANDLER, authorizeHandler); pipeline.addLast(XHR_POLLING_TRANSPORT, xhrPollingTransport); pipeline.addLast(WEB_SOCKET_TRANSPORT, webSocketTransport); pipeline.addLast(FLASH_SOCKET_TRANSPORT, flashSocketTransport); pipeline.addLast(SOCKETIO_ENCODER, socketIOEncoder); }
From source file:wsclient.WebSocketClientRunner.java
License:Apache License
public void run() { EventLoopGroup group = new NioEventLoopGroup(); try {/*from w w w . j a v a 2s . c o m*/ // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00. // If you change it to V00, ping is not supported and remember to change // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline. final WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory .newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders()), browser); final String protocol = uri.getScheme(); int defaultPort; ChannelInitializer<SocketChannel> initializer; // Normal WebSocket if ("ws".equals(protocol)) { initializer = new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("http-codec", new HttpClientCodec()) .addLast("aggregator", new HttpObjectAggregator(8192)) .addLast("ws-handler", handler); } }; defaultPort = 80; // Secure WebSocket } else if ("wss".equals(protocol)) { initializer = new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { SSLEngine engine = WebSocketSslClientContextFactory.getContext().createSSLEngine(); engine.setUseClientMode(true); ch.pipeline().addFirst("ssl", new SslHandler(engine)) .addLast("http-codec", new HttpClientCodec()) .addLast("aggregator", new HttpObjectAggregator(8192)) .addLast("ws-handler", handler); } }; defaultPort = 443; } else { throw new IllegalArgumentException("Unsupported protocol: " + protocol); } Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(initializer); int port = uri.getPort(); // If no port was specified, we'll try the default port: https://tools.ietf.org/html/rfc6455#section-1.7 if (uri.getPort() == -1) { port = defaultPort; } Channel ch = null; try { ch = b.connect(uri.getHost(), port).sync().channel(); handler.handshakeFuture().sync(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); while (true) { synchronized (mon) { mon.wait(); WebSocketFrame frame = new TextWebSocketFrame(sendlonlat); System.out.println("frame: " + frame); System.out.println("sendlonlat: " + sendlonlat); ch.writeAndFlush(frame); } } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { group.shutdownGracefully(); } }
From source file:xyz.kvantum.server.implementation.HTTPSThread.java
License:Apache License
HTTPSThread(final NioClassResolver classResolver) throws KvantumInitializationException { super("https"); this.setPriority(Thread.MAX_PRIORITY); this.workerGroup = classResolver.getClassProvider() .getEventLoopGroup(CoreConfig.Pools.httpsWorkerGroupThreads); this.bossGroup = classResolver.getClassProvider().getEventLoopGroup(CoreConfig.Pools.httpsBossGroupThreads); try {/* w w w . j ava 2 s.co m*/ final KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(new File(CoreConfig.SSL.keyStore)), CoreConfig.SSL.keyStorePassword.toCharArray()); final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509"); keyManagerFactory.init(keyStore, CoreConfig.SSL.keyStorePassword.toCharArray()); final SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagerFactory.getKeyManagers(), null, null); this.serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup) .channel(classResolver.getClassProvider().getServerSocketChannelClass()) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(final SocketChannel ch) throws Exception { final SSLEngine sslEngine = sslContext.createSSLEngine(); sslEngine.setUseClientMode(false); sslEngine.setNeedClientAuth(false); ch.pipeline().addLast(new SslHandler(sslEngine)); ch.pipeline().addLast(new KvantumReadTimeoutHandler()); ch.pipeline().addLast(new ByteArrayEncoder()); ch.pipeline().addLast(new KvantumServerHandler(ProtocolType.HTTPS)); } }); } catch (final NoSuchAlgorithmException | KeyStoreException | IOException | CertificateException | UnrecoverableKeyException | KeyManagementException e) { throw new KvantumInitializationException("Failed to create SSL socket", e); } }