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:PacketReceiver.java

public static void main(String[] args) throws Exception {
    byte[] buffer = "data".getBytes();
    DatagramPacket packet = new DatagramPacket(buffer, buffer.length, new InetSocketAddress("localhost", 5002));
    DatagramSocket socket = new DatagramSocket(5003);
    socket.send(packet);// w  ww .j a v  a2  s.co m
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    DatagramChannel server = DatagramChannel.open();
    server.bind(null);//  w  w w .  ja  va 2s .  c o  m
    NetworkInterface interf = NetworkInterface.getByName(MULTICAST_INTERFACE_NAME);
    server.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);

    String msg = "Hello!";
    ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
    InetSocketAddress group = new InetSocketAddress(MULTICAST_IP, MULTICAST_PORT);

    server.send(buffer, group);
    System.out.println("Sent the   multicast  message: " + msg);
}

From source file:NewFingerServer.java

public static void main(String[] arguments) throws Exception {
    ServerSocketChannel sockChannel = ServerSocketChannel.open();
    sockChannel.configureBlocking(false);

    InetSocketAddress server = new InetSocketAddress("localhost", 79);
    ServerSocket socket = sockChannel.socket();
    socket.bind(server);/*w w w  .  ja  va  2  s  . c o  m*/

    Selector selector = Selector.open();
    sockChannel.register(selector, SelectionKey.OP_ACCEPT);

    while (true) {
        selector.select();
        Set keys = selector.selectedKeys();
        Iterator it = keys.iterator();
        while (it.hasNext()) {
            SelectionKey selKey = (SelectionKey) it.next();
            it.remove();
            if (selKey.isAcceptable()) {
                ServerSocketChannel selChannel = (ServerSocketChannel) selKey.channel();
                ServerSocket selSocket = selChannel.socket();
                Socket connection = selSocket.accept();

                InputStreamReader isr = new InputStreamReader(connection.getInputStream());
                BufferedReader is = new BufferedReader(isr);
                PrintWriter pw = new PrintWriter(new BufferedOutputStream(connection.getOutputStream()), false);
                pw.println("NIO Finger Server");
                pw.flush();
                String outLine = null;
                String inLine = is.readLine();
                if (inLine.length() > 0) {
                    outLine = inLine;
                }
                readPlan(outLine, pw);
                pw.flush();
                pw.close();
                is.close();

                connection.close();
            }
        }
    }
}

From source file:GetWebPageDemo.java

public static void main(String args[]) throws Exception {
    String resource, host, file;//from w  ww .j  a v  a2  s .  com
    int slashPos;

    resource = "www.java2s.com/index.htm";
    slashPos = resource.indexOf('/'); // find host/file separator
    if (slashPos < 0) {
        resource = resource + "/";
        slashPos = resource.indexOf('/');
    }
    file = resource.substring(slashPos); // isolate host and file parts
    host = resource.substring(0, slashPos);
    System.out.println("Host to contact: '" + host + "'");
    System.out.println("File to fetch : '" + file + "'");

    SocketChannel channel = null;

    try {
        Charset charset = Charset.forName("ISO-8859-1");
        CharsetDecoder decoder = charset.newDecoder();
        CharsetEncoder encoder = charset.newEncoder();

        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
        CharBuffer charBuffer = CharBuffer.allocate(1024);

        InetSocketAddress socketAddress = new InetSocketAddress(host, 80);
        channel = SocketChannel.open();
        channel.connect(socketAddress);

        String request = "GET " + file + " \r\n\r\n";
        channel.write(encoder.encode(CharBuffer.wrap(request)));

        while ((channel.read(buffer)) != -1) {
            buffer.flip();
            decoder.decode(buffer, charBuffer, false);
            charBuffer.flip();
            System.out.println(charBuffer);
            buffer.clear();
            charBuffer.clear();
        }
    } catch (UnknownHostException e) {
        System.err.println(e);
    } catch (IOException e) {
        System.err.println(e);
    } finally {
        if (channel != null) {
            try {
                channel.close();
            } catch (IOException ignored) {
            }
        }
    }

    System.out.println("\nDone.");
}

From source file:GetWebPageApp.java

public static void main(String args[]) throws Exception {
    String resource, host, file;/*  ww  w .j a v  a2  s  .com*/
    int slashPos;

    resource = "www.java2s.com/index.htm"; // skip HTTP://
    slashPos = resource.indexOf('/'); // find host/file separator
    if (slashPos < 0) {
        resource = resource + "/";
        slashPos = resource.indexOf('/');
    }
    file = resource.substring(slashPos); // isolate host and file parts
    host = resource.substring(0, slashPos);
    System.out.println("Host to contact: '" + host + "'");
    System.out.println("File to fetch : '" + file + "'");

    SocketChannel channel = null;

    try {
        Charset charset = Charset.forName("ISO-8859-1");
        CharsetDecoder decoder = charset.newDecoder();
        CharsetEncoder encoder = charset.newEncoder();

        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
        CharBuffer charBuffer = CharBuffer.allocate(1024);

        InetSocketAddress socketAddress = new InetSocketAddress(host, 80);
        channel = SocketChannel.open();
        channel.configureBlocking(false);
        channel.connect(socketAddress);

        selector = Selector.open();

        channel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ);

        while (selector.select(500) > 0) {
            Set readyKeys = selector.selectedKeys();
            try {
                Iterator readyItor = readyKeys.iterator();

                while (readyItor.hasNext()) {

                    SelectionKey key = (SelectionKey) readyItor.next();
                    readyItor.remove();
                    SocketChannel keyChannel = (SocketChannel) key.channel();

                    if (key.isConnectable()) {
                        if (keyChannel.isConnectionPending()) {
                            keyChannel.finishConnect();
                        }
                        String request = "GET " + file + " \r\n\r\n";
                        keyChannel.write(encoder.encode(CharBuffer.wrap(request)));
                    } else if (key.isReadable()) {
                        keyChannel.read(buffer);
                        buffer.flip();

                        decoder.decode(buffer, charBuffer, false);
                        charBuffer.flip();
                        System.out.print(charBuffer);

                        buffer.clear();
                        charBuffer.clear();

                    } else {
                        System.err.println("Unknown key");
                    }
                }
            } catch (ConcurrentModificationException e) {
            }
        }
    } catch (UnknownHostException e) {
        System.err.println(e);
    } catch (IOException e) {
        System.err.println(e);
    } finally {
        if (channel != null) {
            try {
                channel.close();
            } catch (IOException ignored) {
            }
        }
    }
    System.out.println("\nDone.");
}

From source file:DaytimeClient.java

public static void main(String args[]) throws java.io.IOException {
    // Figure out the host and port we're going to talk to
    String host = args[0];//from   ww w.jav  a2 s  .  c om
    int port = 13;
    if (args.length > 1)
        port = Integer.parseInt(args[1]);

    // Create a socket to use
    DatagramSocket socket = new DatagramSocket();

    // Specify a 1-second timeout so that receive() does not block forever.
    socket.setSoTimeout(1000);

    // This buffer will hold the response. On overflow, extra bytes are
    // discarded: there is no possibility of a buffer overflow attack here.
    byte[] buffer = new byte[512];
    DatagramPacket packet = new DatagramPacket(buffer, buffer.length, new InetSocketAddress(host, port));

    // Try three times before giving up
    for (int i = 0; i < 3; i++) {
        try {
            // Send an empty datagram to the specified host (and port)
            packet.setLength(0); // make the packet empty
            socket.send(packet); // send it out

            // Wait for a response (or timeout after 1 second)
            packet.setLength(buffer.length); // make room for the response
            socket.receive(packet); // wait for the response

            // Decode and print the response
            System.out.print(new String(buffer, 0, packet.getLength(), "US-ASCII"));
            // We were successful so break out of the retry loop
            break;
        } catch (SocketTimeoutException e) {
            // If the receive call timed out, print error and retry
            System.out.println("No response");
        }
    }

    // We're done with the channel now
    socket.close();
}

From source file:examples.ssh.LocalPF.java

public static void main(String... args) throws Exception {
    SSHClient ssh = new SSHClient();

    ssh.loadKnownHosts();/* w  ww . ja  v  a2 s .  c o m*/

    ssh.connect("localhost");
    try {

        ssh.authPublickey(System.getProperty("user.name"));

        /*
         * _We_ listen on localhost:8080 and forward all connections on to server, which then forwards it to
         * google.com:80
         */

        ssh.newLocalPortForwarder(new InetSocketAddress("localhost", 8080), "google.com", 80).listen();

    } finally {
        ssh.disconnect();
    }
}

From source file:com.barchart.udt.AppServer.java

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

    int port = 9000;

    if (args.length > 1) {
        System.out.println("usage: appserver [server_port]");
        return;//ww w.  ja  v a2  s. co m
    }

    if (args.length == 1) {
        port = Integer.parseInt(args[0]);
    }

    final NetServerSocketUDT acceptorSocket = new NetServerSocketUDT();
    acceptorSocket.bind(new InetSocketAddress(getLocalHost(), port), 256);

    System.out.printf("server is ready at port: %d\n", port);
    System.out.println("server is ready");
    while (true) {

        final Socket clientSocket = acceptorSocket.accept();

        // Start the read ahead background task
        Executors.newSingleThreadExecutor().submit(new Callable<Boolean>() {
            @Override
            public Boolean call() {
                return clientTask(clientSocket);
            }
        });
    }
}

From source file:examples.ssh.X11.java

public static void main(String... args) throws Exception {
    SSHClient ssh = new SSHClient();

    // Compression makes X11 more feasible over slower connections
    // ssh.useCompression();

    ssh.loadKnownHosts();//from  w w  w.j  a  v  a  2s.c  o  m

    /*
     * NOTE: Forwarding incoming X connections to localhost:6000 only works if X is started without the
     * "-nolisten tcp" option (this is usually not the default for good reason)
     */
    ssh.registerX11Forwarder(new SocketForwardingConnectListener(new InetSocketAddress("localhost", 6000)));

    ssh.connect("localhost");
    try {

        ssh.authPublickey(System.getProperty("user.name"));

        Session sess = ssh.startSession();

        /*
         * It is recommendable to send a fake cookie, and in your ConnectListener when a connection comes in replace
         * it with the real one. But here simply one from `xauth list` is being used.
         */
        sess.reqX11Forwarding("MIT-MAGIC-COOKIE-1", "26e8700422fd3efb99a918ce02324e9e", 0);

        Command cmd = sess.exec("firefox");

        new Pipe("stdout", cmd.getInputStream(), System.out).start();
        new Pipe("stderr", cmd.getErrorStream(), System.err).start();

        // Wait for session & X11 channel to get closed
        ssh.getConnection().join();

    } finally {
        ssh.disconnect();
    }
}

From source file:examples.ssh.RemotePF.java

public static void main(String... args) throws Exception {
    SSHClient client = new SSHClient();
    client.loadKnownHosts();//  w w w .  java 2  s.c  o m

    client.connect("localhost");
    try {

        client.authPublickey(System.getProperty("user.name"));

        /*
         * We make _server_ listen on port 8080, which forwards all connections to us as a channel, and we further
         * forward all such channels to google.com:80
         */
        client.getRemotePortForwarder().bind(new Forward(8080), //
                new SocketForwardingConnectListener(new InetSocketAddress("google.com", 80)));

        // Something to hang on to so forwarding stays
        client.getTransport().join();

    } finally {
        client.disconnect();
    }
}