List of usage examples for io.netty.bootstrap Bootstrap connect
public ChannelFuture connect(SocketAddress remoteAddress)
From source file:alluxio.worker.netty.NettyDataServerTest.java
License:Apache License
private RPCResponse request(RPCRequest rpcBlockWriteRequest) throws Exception { InetSocketAddress address = new InetSocketAddress(mNettyDataServer.getBindHost(), mNettyDataServer.getPort()); ClientHandler handler = new ClientHandler(); Bootstrap clientBootstrap = NettyClient.createClientBootstrap(handler); ChannelFuture f = clientBootstrap.connect(address).sync(); Channel channel = f.channel(); try {//w w w. j a v a 2 s .c om SingleResponseListener listener = new SingleResponseListener(); handler.addListener(listener); channel.writeAndFlush(rpcBlockWriteRequest); return listener.get(NettyClient.TIMEOUT_MS, TimeUnit.MILLISECONDS); } finally { channel.close().sync(); } }
From source file:at.yawk.accordion.netty.NettyConnector.java
License:Mozilla Public License
@Override public Optional<Connection> connect(SocketAddress address) { // TODO find a non-hacky method to close channels Collection<Channel> registeredChannels = Collections.synchronizedList(new ArrayList<>()); EventLoopGroup workerGroup = new NioEventLoopGroup() { @Override/*from ww w. j a v a2 s . c om*/ public ChannelFuture register(Channel channel, ChannelPromise promise) { registeredChannels.add(channel); return super.register(channel, promise); } }; AtomicReference<Connection> connectionRef = new AtomicReference<>(); // init Bootstrap bootstrap = new Bootstrap().group(workerGroup).handler(new ChannelHandlerAdapter() { @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { NettyConnection connection = new NettyConnection(ctx.channel()); connectionRef.set(connection); connection.init(); } }).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true); try { // connect ChannelFuture connectFuture = bootstrap.connect(address); // wait for connection connectFuture.sync(); return Optional.of(connectionRef.get()); } catch (Exception e) { // shut down workers workerGroup.shutdownGracefully(); // kill channels registeredChannels.forEach(NettyConnection::close); return Optional.empty(); } }
From source file:at.yawk.dbus.protocol.DbusConnector.java
/** * Connect to the dbus server at the given {@link SocketAddress}. *//*from ww w. ja v a 2 s. c om*/ public DbusChannel connect(SocketAddress address) throws Exception { Bootstrap localBootstrap = bootstrap.clone(); if (address instanceof DomainSocketAddress) { localBootstrap.group(new EpollEventLoopGroup()); localBootstrap.channel(EpollDomainSocketChannel.class); } else { localBootstrap.group(new NioEventLoopGroup()); localBootstrap.channel(NioSocketChannel.class); } Channel channel = localBootstrap.connect(address).sync().channel(); AuthClient authClient = new AuthClient(); if (LoggingInboundAdapter.isEnabled()) { channel.pipeline().addLast(new LoggingInboundAdapter()); } channel.pipeline().addLast("auth", authClient); channel.config().setAutoRead(true); log.trace("Pipeline is now {}", channel.pipeline()); // I really don't get why dbus does this channel.write(Unpooled.wrappedBuffer(new byte[] { 0 })); if (authMechanism == null) { authMechanism = new ExternalAuthMechanism(); } CompletionStage<?> completionPromise = authClient.startAuth(channel, authMechanism); SwappableMessageConsumer swappableConsumer = new SwappableMessageConsumer(initialConsumer); completionPromise.toCompletableFuture().thenRun(() -> { channel.pipeline().replace("auth", "main", new DbusMainProtocol(swappableConsumer)); log.trace("Pipeline is now {}", channel.pipeline()); }).get(); DbusChannelImpl dbusChannel = new DbusChannelImpl(channel, swappableConsumer); dbusChannel.write(MessageFactory.methodCall("/", "org.freedesktop.DBus", "org.freedesktop.DBus", "Hello")); return dbusChannel; }
From source file:bftsmart.communication.client.netty.NettyClientServerCommunicationSystemClientSide.java
License:Apache License
/** * Tulio Ribeiro Connect to specific replica and returns the ChannelFuture. * sessionClientToReplica is replaced with the new connection. Removed redundant * code./*from w w w.java 2s.co m*/ */ public synchronized ChannelFuture connectToReplica(int replicaId, SecretKeyFactory fac) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException { String str = this.clientId + ":" + replicaId; PBEKeySpec spec = TOMUtil.generateKeySpec(str.toCharArray()); SecretKey authKey = fac.generateSecret(spec); Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.option(ChannelOption.TCP_NODELAY, true); b.option(ChannelOption.SO_SNDBUF, tcpSendBufferSize); b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeoutMsec); b.handler(getChannelInitializer()); ChannelFuture channelFuture = b.connect(controller.getRemoteAddress(replicaId)); NettyClientServerSession ncss = new NettyClientServerSession(channelFuture.channel(), replicaId); sessionClientToReplica.put(replicaId, ncss); return channelFuture; }
From source file:books.netty.protocol.http.xml.client.HttpXmlClient.java
License:Apache License
public void connect(int port) throws Exception { // ?NIO//from w ww.j a v a 2 s . co m EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) { ch.pipeline().addLast("http-decoder", new HttpResponseDecoder()); ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536)); // XML? ch.pipeline().addLast("xml-decoder", new HttpXmlResponseDecoder(Order.class, true)); ch.pipeline().addLast("http-encoder", new HttpRequestEncoder()); ch.pipeline().addLast("xml-encoder", new HttpXmlRequestEncoder()); ch.pipeline().addLast("xmlClientHandler", new HttpXmlClientHandle()); } }); // ?? ChannelFuture f = b.connect(new InetSocketAddress(port)).sync(); // f.channel().closeFuture().sync(); } finally { // NIO group.shutdownGracefully(); } }
From source file:ccwihr.client.t1.HttpUploadClient.java
License:Apache License
/** * Standard post without multipart but already support on Factory (memory * management)/*from w ww . ja v a 2 s . c o m*/ * @param se12 * * @return the list of HttpData object (attribute and file) to be reused on * next post */ private static List<InterfaceHttpData> formpost(Bootstrap bootstrap, String host, int port, URI uriSimple, SyncEntity se12, HttpDataFactory factory, List<Entry<String, String>> headers) throws Exception { // XXX /formpost // Start the connection attempt. ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); // Wait until the connection attempt succeeds or fails. Channel channel = future.sync().channel(); // Prepare the HTTP request. HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriSimple.toASCIIString()); // Use the PostBody encoder HttpPostRequestEncoder bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, false); // false // it is legal to add directly header or cookie into the request until // finalize for (Entry<String, String> entry : headers) { request.headers().set(entry.getKey(), entry.getValue()); } // add Form attribute bodyRequestEncoder.addBodyAttribute("getform", "POST"); bodyRequestEncoder.addBodyAttribute("info", "first value"); bodyRequestEncoder.addBodyAttribute("secondinfo", "secondvalue &"); bodyRequestEncoder.addBodyAttribute("thirdinfo", textArea); bodyRequestEncoder.addBodyAttribute("fourthinfo", textAreaLong); // bodyRequestEncoder.addBodyFileUpload("myfile", file, // "application/x-zip-compressed", false); // finalize request request = bodyRequestEncoder.finalizeRequest(); // Create the bodylist to be reused on the last version with Multipart // support List<InterfaceHttpData> bodylist = bodyRequestEncoder.getBodyListAttributes(); // send request channel.write(request); // test if request was chunked and if so, finish the write if (bodyRequestEncoder.isChunked()) { // could do either // request.isChunked() // either do it through ChunkedWriteHandler channel.write(bodyRequestEncoder); } channel.flush(); // Do not clear here since we will reuse the InterfaceHttpData on the // next request // for the example (limit action on client side). Take this as a // broadcast of the same // request on both Post actions. // // On standard program, it is clearly recommended to clean all files // after each request // bodyRequestEncoder.cleanFiles(); // Wait for the server to close the connection. channel.closeFuture().sync(); return bodylist; }
From source file:cn.wcl.test.netty.HttpUploadClient.java
License:Apache License
/** * Standard post without multipart but already support on Factory (memory management) * * @return the list of HttpData object (attribute and file) to be reused on next post *///from ww w . j ava 2 s . c om private static List<InterfaceHttpData> formpost(Bootstrap bootstrap, String host, int port, URI uriSimple, File file, HttpDataFactory factory, List<Entry<String, String>> headers) throws Exception { // XXX /formpost // Start the connection attempt. ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); // Wait until the connection attempt succeeds or fails. Channel channel = future.sync().channel(); // Prepare the HTTP request. HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriSimple.toASCIIString()); // Use the PostBody encoder HttpPostRequestEncoder bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, false); // false => not multipart // it is legal to add directly header or cookie into the request until finalize for (Entry<String, String> entry : headers) { request.headers().set(entry.getKey(), entry.getValue()); } // add Form attribute bodyRequestEncoder.addBodyAttribute("getform", "POST"); bodyRequestEncoder.addBodyAttribute("info", "first value"); bodyRequestEncoder.addBodyAttribute("secondinfo", "secondvalue &"); bodyRequestEncoder.addBodyAttribute("thirdinfo", textArea); bodyRequestEncoder.addBodyAttribute("fourthinfo", textAreaLong); bodyRequestEncoder.addBodyFileUpload("myfile", file, "application/x-zip-compressed", false); // finalize request request = bodyRequestEncoder.finalizeRequest(); // Create the bodylist to be reused on the last version with Multipart support List<InterfaceHttpData> bodylist = bodyRequestEncoder.getBodyListAttributes(); // send request channel.write(request); // test if request was chunked and if so, finish the write if (bodyRequestEncoder.isChunked()) { // could do either request.isChunked() // either do it through ChunkedWriteHandler channel.write(bodyRequestEncoder); } channel.flush(); // Do not clear here since we will reuse the InterfaceHttpData on the next request // for the example (limit action on client side). Take this as a broadcast of the same // request on both Post actions. // // On standard program, it is clearly recommended to clean all files after each request // bodyRequestEncoder.cleanFiles(); // Wait for the server to close the connection. channel.closeFuture().sync(); return bodylist; }
From source file:cn.wcl.test.netty.HttpUploadClient.java
License:Apache License
/** * Multipart example//from ww w. j av a2 s.c o m */ private static void formpostmultipart(Bootstrap bootstrap, String host, int port, URI uriFile, HttpDataFactory factory, Iterable<Entry<String, String>> headers, List<InterfaceHttpData> bodylist) throws Exception { // XXX /formpostmultipart // Start the connection attempt. ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); // Wait until the connection attempt succeeds or fails. Channel channel = future.sync().channel(); // Prepare the HTTP request. HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriFile.toASCIIString()); // Use the PostBody encoder HttpPostRequestEncoder bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, true); // true => multipart // it is legal to add directly header or cookie into the request until finalize for (Entry<String, String> entry : headers) { request.headers().set(entry.getKey(), entry.getValue()); } // add Form attribute from previous request in formpost() bodyRequestEncoder.setBodyHttpDatas(bodylist); // finalize request bodyRequestEncoder.finalizeRequest(); // send request channel.write(request); // test if request was chunked and if so, finish the write if (bodyRequestEncoder.isChunked()) { channel.write(bodyRequestEncoder); } channel.flush(); // Now no more use of file representation (and list of HttpData) bodyRequestEncoder.cleanFiles(); // Wait for the server to close the connection. channel.closeFuture().sync(); }
From source file:cn.yesway.demo.book.protocol.http.xml.client.HttpXmlClient.java
License:Apache License
public void connect(int port) throws Exception { // ?NIO//w ww . j a v a 2 s . co m EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("http-decoder", new HttpResponseDecoder()); ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536)); // XML? ch.pipeline().addLast("xml-decoder", new HttpXmlResponseDecoder(Order.class, true)); ch.pipeline().addLast("http-encoder", new HttpRequestEncoder()); ch.pipeline().addLast("xml-encoder", new HttpXmlRequestEncoder()); ch.pipeline().addLast("xmlClientHandler", new HttpXmlClientHandle()); } }); // ?? ChannelFuture f = b.connect(new InetSocketAddress(port)).sync(); // f.channel().closeFuture().sync(); } finally { // NIO group.shutdownGracefully(); } }
From source file:code.google.nfs.rpc.netty.client.NettyClientFactory.java
License:Apache License
protected Client createClient(String targetIP, int targetPort, int connectTimeout, String key) throws Exception { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(workerGroup).channel(NioSocketChannel.class) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.TCP_NODELAY, Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.nodelay", "true"))) .option(ChannelOption.SO_REUSEADDR, Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.reuseaddress", "true"))); if (connectTimeout < 1000) { bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000); } else {//from ww w.j a va 2 s .co m bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout); } final NettyClientHandler handler = new NettyClientHandler(this, key); bootstrap.handler(new ChannelInitializer<SocketChannel>() { protected void initChannel(SocketChannel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); pipeline.addLast("decoder", new NettyProtocolDecoder()); pipeline.addLast("encoder", new NettyProtocolEncoder()); pipeline.addLast("handler", handler); } }); ChannelFuture future = bootstrap.connect(new InetSocketAddress(targetIP, targetPort)).sync(); future.awaitUninterruptibly(connectTimeout); if (!future.isDone()) { LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " timeout!"); throw new Exception("Create connection to " + targetIP + ":" + targetPort + " timeout!"); } if (future.isCancelled()) { LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!"); throw new Exception("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!"); } if (!future.isSuccess()) { LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " error", future.cause()); throw new Exception("Create connection to " + targetIP + ":" + targetPort + " error", future.cause()); } NettyClient client = new NettyClient(future, key, connectTimeout); handler.setClient(client); return client; }