List of usage examples for io.netty.channel ChannelFuture sync
@Override
ChannelFuture sync() throws InterruptedException;
From source file:com.qq.servlet.demo.netty.sample.telnet.TelnetClient.java
License:Apache License
public void run() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try {/* w ww . j ava2 s .c o m*/ Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new TelnetClientInitializer()); // Start the connection attempt. Channel ch = b.connect(host, port).sync().channel(); ch.writeAndFlush("askfjasfljaslfsajl"); // Read commands from the stdin. ChannelFuture lastWriteFuture = null; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for (;;) { String line = in.readLine(); if (line == null) { break; } // Sends the received line to the server. lastWriteFuture = ch.writeAndFlush(line + "\r\n"); // If user typed the 'bye' command, wait until the server closes // the connection. if ("bye".equals(line.toLowerCase())) { ch.closeFuture().sync(); break; } } // Wait until all messages are flushed before closing the channel. if (lastWriteFuture != null) { lastWriteFuture.sync(); } } finally { group.shutdownGracefully(); } }
From source file:com.qq.servlet.demo.netty.telnet.client.TelnetClient.java
License:Apache License
private void test(Bootstrap b, int i) throws InterruptedException { // Start the connection attempt. Channel ch = b.connect(host, port).sync().channel(); String body = "[" + i + "]aaaaaaa" + Thread.currentThread().getName() + "aaaaa"; AttributeKey<String> key = AttributeKey.valueOf("ASYNC_CONTEXT"); Attribute<String> attr = ch.attr(key); String andSet = attr.getAndSet(Thread.currentThread().getName()); System.out.println(andSet);/*from w w w . ja v a 2 s . co m*/ ChannelFuture lastWriteFuture = ch.writeAndFlush(body + "\r\n"); // Wait until all messages are flushed before closing the channel. if (lastWriteFuture != null) { lastWriteFuture.sync(); } }
From source file:com.qq.servlet.demo.thrift.netty.client.NettyThriftClient.java
License:Apache License
public void run() throws Exception { EventLoopGroup group = new NioEventLoopGroup(2); try {/*ww w .jav a 2 s . c o m*/ final Bootstrap b = new Bootstrap(); b.group(group); b.channel(NioSocketChannel.class); b.handler(new NettyThriftClientInitializer()); // Start the connection attempt. ChannelFuture future = b.connect(host, port); ChannelFuture sync = future.sync(); Channel ch = sync.channel(); AttributeKey<String> key = AttributeKey.valueOf("ASYNC_CONTEXT"); Attribute<String> attr = ch.attr(key); String andSet = attr.getAndSet(Thread.currentThread().getName()); TMemoryBuffer transportr = new TMemoryBuffer(1024); TProtocol protocol = new TBinaryProtocol(transportr); TMultiplexedProtocol multiProtocol3 = new TMultiplexedProtocol(protocol, IdGenService.class.getSimpleName()); IdGenService.Client aoClient = new IdGenService.Client(multiProtocol3); IdGenReq req = new IdGenReq(); req.setTableName("t_lottery_append_task-----------"); req.setSource(andSet); aoClient.send_idGen(req); int length = transportr.length(); byte[] buf = new byte[length]; transportr.read(buf, 0, length); System.out.println(Arrays.toString(buf)); ChannelFuture lastWriteFuture = ch.writeAndFlush(buf); // Wait until all messages are flushed before closing the channel. if (lastWriteFuture != null) { lastWriteFuture.sync(); } System.in.read(); } finally { group.shutdownGracefully(); } }
From source file:com.sixmac.imspeak.app.SecureChatClient.java
License:Apache License
public static void main(String[] args) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try {/* ww w . j a v a 2 s. com*/ Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new SecureChatClientInitializer()); // Start the connection attempt. Channel ch = b.connect(HOST, PORT).sync().channel(); // Read commands from the stdin. ChannelFuture lastWriteFuture = null; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for (;;) { String line = in.readLine(); if (line == null) { break; } // Sends the received line to the server. lastWriteFuture = ch.writeAndFlush(line + "\r\n"); // If user typed the 'bye' command, wait until the server closes // the connection. if ("bye".equals(line.toLowerCase())) { ch.closeFuture().sync(); break; } } // Wait until all messages are flushed before closing the channel. if (lastWriteFuture != null) { lastWriteFuture.sync(); } } finally { // The connection is closed automatically on shutdown. group.shutdownGracefully(); } }
From source file:com.sunan.van.client.TestVanClient.java
License:Apache License
public void run() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try {/*from ww w . j a v a2 s. c o m*/ Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new TelnetClientInitializer()); // Start the connection attempt. Channel ch = b.connect(host, port).sync().channel(); register(DEFAULT_TOPIC, ch); // Read commands from the stdin. ChannelFuture lastWriteFuture = null; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for (;;) { String line = in.readLine(); if (line == null) { break; } // Sends the received line to the server. lastWriteFuture = ch.writeAndFlush(line + "\r\n"); // If user typed the 'bye' command, wait until the server closes // the connection. if ("bye".equals(line.toLowerCase())) { ch.closeFuture().sync(); break; } } // Wait until all messages are flushed before closing the channel. if (lastWriteFuture != null) { lastWriteFuture.sync(); } } finally { group.shutdownGracefully(); } }
From source file:com.tc.websocket.server.DominoWebSocketServer.java
License:Apache License
@Override public synchronized void start() { if (this.isOn()) return;/*from w w w . j av a 2 s.c o m*/ try { try { ServerBootstrap boot = new ServerBootstrap(); if (cfg.isNativeTransport()) { boot.channel(EpollServerSocketChannel.class); } else { boot.channel(NioServerSocketChannel.class); } boot.group(bossGroup, workerGroup).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(8 * 1024, 32 * 1024)) .childOption(ChannelOption.SO_SNDBUF, cfg.getSendBuffer()) .childOption(ChannelOption.SO_RCVBUF, cfg.getReceiveBuffer()) .childOption(ChannelOption.TCP_NODELAY, true).childHandler(init); //bind to the main port boot.bind(cfg.getPort()).sync(); //bind to the redirect port (e.g. 80 will redirect to 443) for (Integer port : cfg.getRedirectPorts()) { ChannelFuture f = boot.bind(port); f.sync(); } this.on.set(true); String version = BundleUtils.getVersion(Activator.bundle); String name = BundleUtils.getName(Activator.bundle); cfg.print(name + " ready and listening on " + cfg.getPort() + " running version " + version); } finally { } } catch (Exception e) { LOG.log(Level.SEVERE, null, e); } }
From source file:com.tch.test.chat.netty.NettyClient.java
License:Apache License
public static void main(String[] args) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try {/*from w w w. j a va 2 s. com*/ Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new MyClientChannelInitializer()); // Start the connection attempt. Channel ch = b.connect(HOST, PORT).sync().channel(); // Read commands from the stdin. ChannelFuture lastWriteFuture = null; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for (;;) { String line = in.readLine(); if (line == null) { break; } // Sends the received line to the server. lastWriteFuture = ch.writeAndFlush(line + "\r\n"); // If user typed the 'bye' command, wait until the server closes // the connection. if ("bye".equals(line.toLowerCase())) { ch.closeFuture().sync(); break; } } // Wait until all messages are flushed before closing the channel. if (lastWriteFuture != null) { lastWriteFuture.sync(); } } finally { // The connection is closed automatically on shutdown. group.shutdownGracefully(); } }
From source file:com.tesora.dve.tools.libmy.AsyncExample.java
License:Open Source License
public static void main(String[] args) throws Exception { final String mysqlHost = "localhost"; final int mysqlPort = 3307; final String username = "root"; final String password = "password"; final boolean isClearText = true; final InetSocketAddress serverAddress = new InetSocketAddress(mysqlHost, mysqlPort); final MyBackendDecoder.CharsetDecodeHelper charsetHelper = constructCharsetDecodeHelper(); final SimpleCredentials cred = constructCredentials(username, password, isClearText); final JavaCharsetCatalog javaCharsetCatalog = constructJavaCharsetCatalog(); final MysqlClientAuthenticationHandler authHandler = new MysqlClientAuthenticationHandler(cred, ClientCapabilities.DEFAULT_PSITE_CAPABILITIES, javaCharsetCatalog, new AtomicReference<Charset>()); final NioEventLoopGroup connectionEventGroup = new NioEventLoopGroup(1); final Bootstrap mysqlBootstrap = new Bootstrap(); mysqlBootstrap // .group(inboundChannel.eventLoop()) .channel(NioSocketChannel.class).group(connectionEventGroup) .option(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT) .handler(new ChannelInitializer<Channel>() { @Override//from w w w . ja v a 2 s . c o m protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(authHandler).addLast(MyBackendDecoder.class.getSimpleName(), new MyBackendDecoder(charsetHelper)).addLast(new ChannelDuplexHandler() { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { System.out.println("WRITE:" + msg); super.write(ctx, msg, promise); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof MyFieldPktResponse) { final MyFieldPktResponse myFieldPktResponse = (MyFieldPktResponse) msg; System.out.println("COLUMN: " + myFieldPktResponse.getOrig_column() + "," + myFieldPktResponse.getColumn_type()); } else if (msg instanceof MyTextResultRow) { final StringBuilder builder = new StringBuilder(); builder.append("ROW:"); final MyTextResultRow textRow = (MyTextResultRow) msg; for (int i = 0; i < textRow.size(); i++) { builder.append('\t'); builder.append(textRow.getString(i)); } System.out.println(builder.toString()); } super.channelRead(ctx, msg); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { super.channelInactive(ctx); System.out.println("CLOSE. "); } }); } }); final ChannelFuture connectFut = mysqlBootstrap.connect(serverAddress); connectFut.sync(); System.out.println("Waiting to finish authenticate handshake"); authHandler.assertAuthenticated();//don't write a request until you know the login is complete. System.out.println("Connected, and authenticated, getting channel to write requests"); final Channel chan = connectFut.channel(); System.out.println("Sending two pipelined requests without blocking for first response."); chan.write(MSPComQueryRequestMessage.newMessage("show databases", CharsetUtil.UTF_8)); chan.write( MSPComQueryRequestMessage.newMessage("select * from information_schema.tables", CharsetUtil.UTF_8)); chan.flush();//NOTE: nothing is sent until this is called. Use writeAndFlush if you want it to go out immediately. System.out.println("Sleeping 5 sec so all results come back"); //normally you would sync to responses here. TimeUnit.SECONDS.sleep(5); System.out.println("Closing socket."); chan.writeAndFlush(MSPComQuitRequestMessage.newMessage());//send friendly hangup message. Probably correct to also wait for server close or an OK packet. chan.close(); chan.closeFuture().sync(); System.out.println("Exiting."); System.exit(0); }
From source file:com.topsec.bdc.platform.api.test.http.upload.HttpUploadClient.java
License:Apache License
/** * Standard post without multipart but already support on Factory (memory management) * //from w w w . ja v a2 s . c om * @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, 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:com.topsec.bdc.platform.api.test.http.upload.HttpUploadClient.java
License:Apache License
/** * Multipart example// www .java2 s. c o m */ private static void formpostmultipart(Bootstrap bootstrap, String host, int port, URI uriFile, HttpDataFactory factory, List<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(); }