List of usage examples for io.netty.util.internal SocketUtils socketAddress
public static InetSocketAddress socketAddress(final String hostname, final int port)
From source file:com.cmz.http.upload.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 *//* www.j a v a2 s . c o m*/ 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(SocketUtils.socketAddress(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.cmz.http.upload.HttpUploadClient.java
License:Apache License
/** * Multipart example/*from w w w .ja v a 2 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(SocketUtils.socketAddress(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:com.cmz.sctp.multihoming.SctpMultiHomingEchoClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try {/*from w w w. ja v a 2 s . com*/ Bootstrap b = new Bootstrap(); b.group(group).channel(NioSctpChannel.class).option(SctpChannelOption.SCTP_NODELAY, true) .handler(new ChannelInitializer<SctpChannel>() { @Override public void initChannel(SctpChannel ch) throws Exception { ch.pipeline().addLast( // new LoggingHandler(LogLevel.INFO), new SctpEchoClientHandler()); } }); InetSocketAddress localAddress = SocketUtils.socketAddress(CLIENT_PRIMARY_HOST, CLIENT_PORT); InetAddress localSecondaryAddress = SocketUtils.addressByName(CLIENT_SECONDARY_HOST); InetSocketAddress remoteAddress = SocketUtils.socketAddress(SERVER_REMOTE_HOST, SERVER_REMOTE_PORT); // Bind the client channel. ChannelFuture bindFuture = b.bind(localAddress).sync(); // Get the underlying sctp channel SctpChannel channel = (SctpChannel) bindFuture.channel(); // Bind the secondary address. // Please note that, bindAddress in the client channel should be done before connecting if you have not // enable Dynamic Address Configuration. See net.sctp.addip_enable kernel param channel.bindAddress(localSecondaryAddress).sync(); // Finish connect ChannelFuture connectFuture = channel.connect(remoteAddress).sync(); // Wait until the connection is closed. connectFuture.channel().closeFuture().sync(); } finally { // Shut down the event loop to terminate all threads. group.shutdownGracefully(); } }
From source file:com.cmz.sctp.multihoming.SctpMultiHomingEchoServer.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {/*from w ww . j av a 2s . c o m*/ ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioSctpServerChannel.class) .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SctpChannel>() { @Override public void initChannel(SctpChannel ch) throws Exception { ch.pipeline().addLast( // new LoggingHandler(LogLevel.INFO), new SctpEchoServerHandler()); } }); InetSocketAddress localAddress = SocketUtils.socketAddress(SERVER_PRIMARY_HOST, SERVER_PORT); InetAddress localSecondaryAddress = SocketUtils.addressByName(SERVER_SECONDARY_HOST); // Bind the server to primary address. ChannelFuture bindFuture = b.bind(localAddress).sync(); //Get the underlying sctp channel SctpServerChannel channel = (SctpServerChannel) bindFuture.channel(); //Bind the secondary address ChannelFuture connectFuture = channel.bindAddress(localSecondaryAddress).sync(); // Wait until the connection is closed. connectFuture.channel().closeFuture().sync(); } finally { // Shut down all event loops to terminate all threads. bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.flysoloing.learning.network.netty.qotm.QuoteOfTheMomentClient.java
License:Apache License
public static void main(String[] args) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try {// w w w.j ava 2 s. co m Bootstrap b = new Bootstrap(); b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true) .handler(new QuoteOfTheMomentClientHandler()); Channel ch = b.bind(0).sync().channel(); // Broadcast the QOTM request to port 8080. ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("QOTM?", CharsetUtil.UTF_8), SocketUtils.socketAddress("255.255.255.255", PORT))).sync(); // QuoteOfTheMomentClientHandler will close the DatagramChannel when a // response is received. If the channel is not closed within 5 seconds, // print an error message and quit. if (!ch.closeFuture().await(5000)) { System.err.println("QOTM request timed out."); } } finally { group.shutdownGracefully(); } }
From source file:com.flysoloing.learning.network.netty.udt.echo.rendezvous.MsgEchoPeerOne.java
License:Apache License
public static void main(final String[] args) throws Exception { final int messageSize = 64 * 1024; final InetSocketAddress self = SocketUtils.socketAddress(Config.hostOne, Config.portOne); final InetSocketAddress peer = SocketUtils.socketAddress(Config.hostTwo, Config.portTwo); new MsgEchoPeerOne(self, peer, messageSize).run(); }
From source file:com.flysoloing.learning.network.netty.udt.echo.rendezvous.MsgEchoPeerTwo.java
License:Apache License
public static void main(final String[] args) throws Exception { final int messageSize = 64 * 1024; final InetSocketAddress self = SocketUtils.socketAddress(Config.hostTwo, Config.portTwo); final InetSocketAddress peer = SocketUtils.socketAddress(Config.hostOne, Config.portOne); new MsgEchoPeerTwo(self, peer, messageSize).run(); }
From source file:com.flysoloing.learning.network.netty.udt.echo.rendezvousBytes.ByteEchoPeerOne.java
License:Apache License
public static void main(String[] args) throws Exception { final int messageSize = 64 * 1024; final InetSocketAddress myAddress = SocketUtils.socketAddress(Config.hostOne, Config.portOne); final InetSocketAddress peerAddress = SocketUtils.socketAddress(Config.hostTwo, Config.portTwo); new ByteEchoPeerOne(messageSize, myAddress, peerAddress).run(); }
From source file:com.flysoloing.learning.network.netty.udt.echo.rendezvousBytes.ByteEchoPeerTwo.java
License:Apache License
public static void main(String[] args) throws Exception { final int messageSize = 64 * 1024; final InetSocketAddress myAddress = SocketUtils.socketAddress(Config.hostTwo, Config.portTwo); final InetSocketAddress peerAddress = SocketUtils.socketAddress(Config.hostOne, Config.portOne); new ByteEchoPeerTwo(messageSize, myAddress, peerAddress).run(); }
From source file:io.vertx.core.dns.impl.netty.UnixResolverDnsServerAddressStreamProvider.java
License:Apache License
private static Map<String, DnsServerAddresses> parse(File... etcResolverFiles) throws IOException { Map<String, DnsServerAddresses> domainToNameServerStreamMap = new HashMap<String, DnsServerAddresses>( etcResolverFiles.length << 1); for (File etcResolverFile : etcResolverFiles) { if (!etcResolverFile.isFile()) { continue; }/*from ww w . j a va 2s. com*/ FileReader fr = new FileReader(etcResolverFile); BufferedReader br = null; try { br = new BufferedReader(fr); List<InetSocketAddress> addresses = new ArrayList<InetSocketAddress>(2); String domainName = etcResolverFile.getName(); int port = DNS_PORT; String line; while ((line = br.readLine()) != null) { line = line.trim(); char c; if (line.isEmpty() || (c = line.charAt(0)) == '#' || c == ';') { continue; } if (line.startsWith(NAMESERVER_ROW_LABEL)) { int i = indexOfNonWhiteSpace(line, NAMESERVER_ROW_LABEL.length()); if (i < 0) { throw new IllegalArgumentException("error parsing label " + NAMESERVER_ROW_LABEL + " in file " + etcResolverFile + ". value: " + line); } String maybeIP = line.substring(i); // There may be a port appended onto the IP address so we attempt to extract it. if (!NetUtil.isValidIpV4Address(maybeIP) && !NetUtil.isValidIpV6Address(maybeIP)) { i = maybeIP.lastIndexOf('.'); if (i + 1 >= maybeIP.length()) { throw new IllegalArgumentException("error parsing label " + NAMESERVER_ROW_LABEL + " in file " + etcResolverFile + ". invalid IP value: " + line); } port = Integer.parseInt(maybeIP.substring(i + 1)); maybeIP = maybeIP.substring(0, i); } addresses.add(SocketUtils.socketAddress(maybeIP, port)); } else if (line.startsWith(DOMAIN_ROW_LABEL)) { int i = indexOfNonWhiteSpace(line, DOMAIN_ROW_LABEL.length()); if (i < 0) { throw new IllegalArgumentException("error parsing label " + DOMAIN_ROW_LABEL + " in file " + etcResolverFile + " value: " + line); } domainName = line.substring(i); if (!addresses.isEmpty()) { putIfAbsent(domainToNameServerStreamMap, domainName, addresses); } addresses = new ArrayList<InetSocketAddress>(2); } else if (line.startsWith(PORT_ROW_LABEL)) { int i = indexOfNonWhiteSpace(line, PORT_ROW_LABEL.length()); if (i < 0) { throw new IllegalArgumentException("error parsing label " + PORT_ROW_LABEL + " in file " + etcResolverFile + " value: " + line); } port = Integer.parseInt(line.substring(i)); } else if (line.startsWith(SORTLIST_ROW_LABEL)) { logger.info("row type {} not supported. ignoring line: {}", SORTLIST_ROW_LABEL, line); } } if (!addresses.isEmpty()) { putIfAbsent(domainToNameServerStreamMap, domainName, addresses); } } finally { if (br == null) { fr.close(); } else { br.close(); } } } return domainToNameServerStreamMap; }