Example usage for java.net InetSocketAddress InetSocketAddress

List of usage examples for java.net InetSocketAddress InetSocketAddress

Introduction

In this page you can find the example usage for java.net InetSocketAddress InetSocketAddress.

Prototype

private InetSocketAddress(int port, String hostname) 

Source Link

Usage

From source file:com.ok2c.lightmtp.examples.LocalMailServerTransportExample.java

public static void main(final String[] args) throws Exception {
    File workingDir = new File(".");
    IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(1).build();

    final MailServerTransport mta = new LocalMailServerTransport(workingDir, config);

    InetSocketAddress sockaddress = new InetSocketAddress("localhost", 2525);

    InetAddressRange iprange = new InetAddressRange(InetAddress.getByName("127.0.0.0"), 8);

    mta.start(new DefaultIdGenerator(), new MyRemoteAddressValidator(iprange), new MyEnvelopValidator(),
            new MyDeliveryHandler());
    mta.listen(sockaddress);// ww  w .ja  v  a  2s.  c  o m

    System.out.println("LMTP server listening on " + sockaddress);

    Runtime runtime = Runtime.getRuntime();
    runtime.addShutdownHook(new Thread() {

        @Override
        public void run() {
            try {
                mta.shutdown();
            } catch (IOException ex) {
                mta.forceShutdown();
            }
        }

    });
}

From source file:async.nio2.Main.java

public static void main(String[] args) throws IOException, InterruptedException, ExecutionException {

    if (args.length == 3) {
        PORT = Integer.valueOf(args[0]);
        NO_CLIENTS = Integer.valueOf(args[1]);
        NO_SAMPLES = Integer.valueOf(args[2]);
    }//from   w ww . ja  v  a2  s.co  m

    if (PORT < 0) {
        System.err.println("Error: port < 0");
        System.exit(1);
    }

    if (NO_CLIENTS < 1) {
        System.err.println("Error: #clients < 1");
        System.exit(1);
    }

    if (NO_SAMPLES < 1) {
        System.err.println("Error: #samples < 1");
        System.exit(1);
    }

    AsynchronousChannelGroup groupServer = AsynchronousChannelGroup
            .withThreadPool(Executors.newFixedThreadPool(1));
    AsynchronousChannelGroup groupClient = AsynchronousChannelGroup
            .withThreadPool(Executors.newFixedThreadPool(1));

    Server server = Server.newInstance(new InetSocketAddress("localhost", PORT), groupServer);
    InetSocketAddress localAddress = server.getLocalAddress();
    String hostname = localAddress.getHostName();
    int port = localAddress.getPort();

    ExecutorService es = Executors.newFixedThreadPool(2);

    System.out.printf("%03d clients on %s:%d, %03d runs each. All times in s.%n", NO_CLIENTS, hostname, port,
            NO_SAMPLES);
    range(0, NO_CLIENTS).unordered().parallel()
            .mapToObj(i -> CompletableFuture.supplyAsync(newClient(localAddress, groupClient), es).join())
            .map(array -> Arrays.stream(array).reduce(new DescriptiveStatistics(), Main::accumulate,
                    Main::combine))
            .map(Main::toEvaluationString).forEach(System.out::println);

    es.shutdown();
    es.awaitTermination(5, TimeUnit.SECONDS);

    groupClient.shutdown();
    groupClient.awaitTermination(5, TimeUnit.SECONDS);

    server.close();
    groupServer.shutdown();
    groupServer.awaitTermination(5, TimeUnit.SECONDS);
}

From source file:com.ok2c.lightmtp.examples.SendMailExample.java

public static void main(final String[] args) throws Exception {

    if (args.length < 3) {
        System.out.println("Usage: sender recipient1[;recipient2;recipient3;...] file");
        System.exit(0);//from  w  w  w .j a  v  a 2s  . co m
    }

    String sender = args[0];
    List<String> recipients = new ArrayList<String>();
    StringTokenizer tokenizer = new StringTokenizer(args[1], ";");
    while (tokenizer.hasMoreTokens()) {
        String s = tokenizer.nextToken();
        s = s.trim();
        if (s.length() > 0) {
            recipients.add(s);
        }
    }

    File src = new File(args[2]);
    if (!src.exists()) {
        System.out.println("File '" + src + "' does not exist");
        System.exit(0);
    }

    DeliveryRequest request = new BasicDeliveryRequest(sender, recipients, new FileSource(src));

    MailUserAgent mua = new DefaultMailUserAgent(TransportType.SMTP, IOReactorConfig.DEFAULT);
    mua.start();

    try {

        InetSocketAddress address = new InetSocketAddress("localhost", 2525);

        Future<DeliveryResult> future = mua.deliver(new SessionEndpoint(address), 0, request, null);

        DeliveryResult result = future.get();
        System.out.println("Delivery result: " + result);

    } finally {
        mua.shutdown();
    }
}

From source file:com.sm.test.TestConnect.java

public static void main(String[] args) throws Exception {
    String[] opts = new String[] { "-host", "-port", "-times" };
    String[] defaults = new String[] { "ssusd003.ir.dc", "6666", "500" };
    String[] paras = getOpts(args, opts, defaults);
    String host = paras[0];/*w ww  .  j  a v  a 2 s .c o m*/
    int port = Integer.valueOf(paras[1]);
    int timeout = Integer.valueOf(paras[2]);

    //        logger.info("pos="+"/test/".indexOf("/"));
    //        logger.info("/test/".substring(0, "/test/".indexOf("/")));
    //        BuildClusterNodes bc = new BuildClusterNodes("./clusterStore/src/test/resources/config.xml");
    //        logger.info(bc.build().toString());
    //        BuildStoreConfig bs = new BuildStoreConfig("./clusterStore/src/test/resources/config.xml");
    //        logger.info(bs.build().toString());
    long begin = System.currentTimeMillis();
    SocketAddress inet = new InetSocketAddress(host, port);
    try {

        Socket socket = new Socket();
        socket.connect(inet, timeout);
        socket.close();
    } catch (Exception ex) {
        logger.error("ex " + ex.toString());
    }
    logger.info("time in Socket ms " + (System.currentTimeMillis() - begin));
    //        begin = System.currentTimeMillis();
    //        try {
    //            TCPClient client = TCPClient.start(host, port);
    //            client.close();
    //        } catch (Exception ex) {
    //            logger.error( ex.getMessage());
    //        }
    //        logger.info("time in TCPClient ms "+(System.currentTimeMillis() - begin));

}

From source file:HttpGet.java

public static void main(String[] args) {
    SocketChannel server = null; // Channel for reading from server
    FileOutputStream outputStream = null; // Stream to destination file
    WritableByteChannel destination; // Channel to write to it

    try { // Exception handling and channel closing code follows this block

        // Parse the URL. Note we use the new java.net.URI, not URL here.
        URI uri = new URI(args[0]);

        // Now query and verify the various parts of the URI
        String scheme = uri.getScheme();
        if (scheme == null || !scheme.equals("http"))
            throw new IllegalArgumentException("Must use 'http:' protocol");

        String hostname = uri.getHost();

        int port = uri.getPort();
        if (port == -1)
            port = 80; // Use default port if none specified

        String path = uri.getRawPath();
        if (path == null || path.length() == 0)
            path = "/";

        String query = uri.getRawQuery();
        query = (query == null) ? "" : '?' + query;

        // Combine the hostname and port into a single address object.
        // java.net.SocketAddress and InetSocketAddress are new in Java 1.4
        SocketAddress serverAddress = new InetSocketAddress(hostname, port);

        // Open a SocketChannel to the server
        server = SocketChannel.open(serverAddress);

        // Put together the HTTP request we'll send to the server.
        String request = "GET " + path + query + " HTTP/1.1\r\n" + // The request
                "Host: " + hostname + "\r\n" + // Required in HTTP 1.1
                "Connection: close\r\n" + // Don't keep connection open
                "User-Agent: " + HttpGet.class.getName() + "\r\n" + "\r\n"; // Blank
                                                                            // line
                                                                            // indicates
                                                                            // end of
                                                                            // request
                                                                            // headers

        // Now wrap a CharBuffer around that request string
        CharBuffer requestChars = CharBuffer.wrap(request);

        // Get a Charset object to encode the char buffer into bytes
        Charset charset = Charset.forName("ISO-8859-1");

        // Use the charset to encode the request into a byte buffer
        ByteBuffer requestBytes = charset.encode(requestChars);

        // Finally, we can send this HTTP request to the server.
        server.write(requestBytes);/*www.  java2  s  . c  o  m*/

        // Set up an output channel to send the output to.
        if (args.length > 1) { // Use a specified filename
            outputStream = new FileOutputStream(args[1]);
            destination = outputStream.getChannel();
        } else
            // Or wrap a channel around standard out
            destination = Channels.newChannel(System.out);

        // Allocate a 32 Kilobyte byte buffer for reading the response.
        // Hopefully we'll get a low-level "direct" buffer
        ByteBuffer data = ByteBuffer.allocateDirect(32 * 1024);

        // Have we discarded the HTTP response headers yet?
        boolean skippedHeaders = false;
        // The code sent by the server
        int responseCode = -1;

        // Now loop, reading data from the server channel and writing it
        // to the destination channel until the server indicates that it
        // has no more data.
        while (server.read(data) != -1) { // Read data, and check for end
            data.flip(); // Prepare to extract data from buffer

            // All HTTP reponses begin with a set of HTTP headers, which
            // we need to discard. The headers end with the string
            // "\r\n\r\n", or the bytes 13,10,13,10. If we haven't already
            // skipped them then do so now.
            if (!skippedHeaders) {
                // First, though, read the HTTP response code.
                // Assume that we get the complete first line of the
                // response when the first read() call returns. Assume also
                // that the first 9 bytes are the ASCII characters
                // "HTTP/1.1 ", and that the response code is the ASCII
                // characters in the following three bytes.
                if (responseCode == -1) {
                    responseCode = 100 * (data.get(9) - '0') + 10 * (data.get(10) - '0')
                            + 1 * (data.get(11) - '0');

                    // If there was an error, report it and quit
                    // Note that we do not handle redirect responses.
                    if (responseCode < 200 || responseCode >= 300) {
                        System.err.println("HTTP Error: " + responseCode);
                        System.exit(1);
                    }
                }

                // Now skip the rest of the headers.
                try {
                    for (;;) {
                        if ((data.get() == 13) && (data.get() == 10) && (data.get() == 13)
                                && (data.get() == 10)) {
                            skippedHeaders = true;
                            break;
                        }
                    }
                } catch (BufferUnderflowException e) {
                    // If we arrive here, it means we reached the end of
                    // the buffer and didn't find the end of the headers.
                    // There is a chance that the last 1, 2, or 3 bytes in
                    // the buffer were the beginning of the \r\n\r\n
                    // sequence, so back up a bit.
                    data.position(data.position() - 3);
                    // Now discard the headers we have read
                    data.compact();
                    // And go read more data from the server.
                    continue;
                }
            }

            // Write the data out; drain the buffer fully.
            while (data.hasRemaining())
                destination.write(data);

            // Now that the buffer is drained, put it into fill mode
            // in preparation for reading more data into it.
            data.clear(); // data.compact() also works here
        }
    } catch (Exception e) { // Report any errors that arise
        System.err.println(e);
        System.err.println("Usage: java HttpGet <URL> [<filename>]");
    } finally { // Close the channels and output file stream, if needed
        try {
            if (server != null && server.isOpen())
                server.close();
            if (outputStream != null)
                outputStream.close();
        } catch (IOException e) {
        }
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    InetAddress serverIPAddress = InetAddress.getByName("localhost");
    int port = 19000;
    InetSocketAddress serverAddress = new InetSocketAddress(serverIPAddress, port);
    Selector selector = Selector.open();
    SocketChannel channel = SocketChannel.open();
    channel.configureBlocking(false);//from w  w w  .  j a  v a 2 s.c  o m
    channel.connect(serverAddress);
    int operations = SelectionKey.OP_CONNECT | SelectionKey.OP_READ | SelectionKey.OP_WRITE;
    channel.register(selector, operations);

    userInputReader = new BufferedReader(new InputStreamReader(System.in));
    while (true) {
        if (selector.select() > 0) {
            boolean doneStatus = processReadySet(selector.selectedKeys());
            if (doneStatus) {
                break;
            }
        }
    }
    channel.close();
}

From source file:org.graylog.plugins.beats.ConsolePrinter.java

public static void main(String[] args) {
    String hostname = "127.0.0.1";
    int port = 5044;
    if (args.length >= 2) {
        hostname = args[0];/*from   w  w  w. j a  va 2 s .  co  m*/
        port = firstNonNull(Ints.tryParse(args[1]), 5044);
    }
    if (args.length >= 1) {
        port = firstNonNull(Ints.tryParse(args[1]), 5044);
    }

    final ChannelFactory factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool());
    final ServerBootstrap b = new ServerBootstrap(factory);
    b.getPipeline().addLast("beats-frame-decoder", new BeatsFrameDecoder());
    b.getPipeline().addLast("beats-codec", new BeatsCodecHandler());
    b.getPipeline().addLast("logging", new LoggingHandler());
    System.out.println("Starting listener on " + hostname + ":" + port);
    b.bind(new InetSocketAddress(hostname, port));
}

From source file:com.ok2c.lightmtp.examples.MailUserAgentExample.java

public static void main(final String[] args) throws Exception {

    String text1 = "From: root\r\n" + "To: testuser1\r\n" + "Subject: test message 1\r\n" + "\r\n"
            + "This is a short test message 1\r\n";
    String text2 = "From: root\r\n" + "To: testuser1, testuser2\r\n" + "Subject: test message 2\r\n" + "\r\n"
            + "This is a short test message 2\r\n";
    String text3 = "From: root\r\n" + "To: testuser1, testuser2, testuser3\r\n" + "Subject: test message 3\r\n"
            + "\r\n" + "This is a short test message 3\r\n";

    List<DeliveryRequest> requests = new ArrayList<DeliveryRequest>();
    requests.add(new BasicDeliveryRequest("root", Arrays.asList("testuser1"),
            new ByteArraySource(text1.getBytes("US-ASCII"))));
    requests.add(new BasicDeliveryRequest("root", Arrays.asList("testuser1", "testuser2"),
            new ByteArraySource(text2.getBytes("US-ASCII"))));
    requests.add(new BasicDeliveryRequest("root", Arrays.asList("testuser1", "testuser2", "testuser3"),
            new ByteArraySource(text3.getBytes("US-ASCII"))));

    MailUserAgent mua = new DefaultMailUserAgent(TransportType.SMTP, IOReactorConfig.DEFAULT);
    mua.start();/*  w w w. j a va  2s. c o m*/

    try {

        InetSocketAddress address = new InetSocketAddress("localhost", 2525);

        Queue<Future<DeliveryResult>> queue = new LinkedList<Future<DeliveryResult>>();
        for (DeliveryRequest request : requests) {
            queue.add(mua.deliver(new SessionEndpoint(address), 0, request, null));
        }

        while (!queue.isEmpty()) {
            Future<DeliveryResult> future = queue.remove();
            DeliveryResult result = future.get();
            System.out.println("Delivery result: " + result);
        }

    } finally {
        mua.shutdown();
    }
}

From source file:com.lxf.spider.client.ClientExecuteSOCKS.java

public static void main(String[] args) throws Exception {
    Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", new MyConnectionSocketFactory()).build();
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg);
    CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
    try {//w w  w .  j  a  v  a  2s . c o m
        InetSocketAddress socksaddr = new InetSocketAddress("mysockshost", 1234);
        HttpClientContext context = HttpClientContext.create();
        context.setAttribute("socks.address", socksaddr);

        HttpHost target = new HttpHost("localhost", 80, "http");
        HttpGet request = new HttpGet("/");

        System.out.println("Executing request " + request + " to " + target + " via SOCKS proxy " + socksaddr);
        CloseableHttpResponse response = httpclient.execute(target, request);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:interoperabilite.webservice.client.ClientExecuteSOCKS.java

public static void main(String[] args) throws Exception {
    Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", new MyConnectionSocketFactory()).build();
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg);
    CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
    try {//  w ww . j av a 2  s.c o m
        InetSocketAddress socksaddr = new InetSocketAddress("mysockshost", 1234);
        HttpClientContext context = HttpClientContext.create();
        context.setAttribute("socks.address", socksaddr);

        HttpHost target = new HttpHost("httpbin.org", 80, "http");
        HttpGet request = new HttpGet("/");

        System.out.println("Executing request " + request + " to " + target + " via SOCKS proxy " + socksaddr);
        CloseableHttpResponse response = httpclient.execute(target, request, context);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}