Example usage for java.nio.channels SocketChannel getLocalAddress

List of usage examples for java.nio.channels SocketChannel getLocalAddress

Introduction

In this page you can find the example usage for java.nio.channels SocketChannel getLocalAddress.

Prototype

@Override
public abstract SocketAddress getLocalAddress() throws IOException;

Source Link

Document

If there is a security manager set, its checkConnect method is called with the local address and -1 as its arguments to see if the operation is allowed.

Usage

From source file:Main.java

License:asdf

public static void main(String args[]) throws Exception {
    Socket s = new Socket("internic.net", 43);
    InputStream in = s.getInputStream();
    OutputStream out = s.getOutputStream();
    String str = "asdfasdfasdf\n";
    byte buf[] = str.getBytes();
    out.write(buf);/* w ww  .  j a v a2 s  .  c  o  m*/
    int c;
    while ((c = in.read()) != -1) {
        System.out.print((char) c);
    }

    SocketChannel socketChannel = s.getChannel();
    System.out.println(socketChannel.getLocalAddress());

    s.close();
}

From source file:org.jenkinsci.remoting.protocol.ProtocolStackLoopbackLoadStress.java

private void startClient(int n, SocketAddress serverAddress, final int clientIntervalMs, boolean ssl)
        throws IOException, ExecutionException, InterruptedException {
    SocketChannel toServer = SocketChannel.open();
    toServer.connect(serverAddress);/*from   ww w. j av  a 2  s.c  o  m*/
    SSLEngine sslEngine = context.createSSLEngine();
    sslEngine.setUseClientMode(true);
    final Channel clientChannel = ProtocolStack.on(new NIONetworkLayer(hub, toServer, toServer))
            .named(String.format("Client %d:  %s -> %s", n, toServer.getLocalAddress(), serverAddress))
            .filter(new AckFilterLayer()).filter(ssl ? new SSLEngineFilterLayer(sslEngine, null) : null)
            .filter(new ConnectionHeadersFilterLayer(Collections.singletonMap("id", "client"),
                    new ConnectionHeadersFilterLayer.Listener() {
                        @Override
                        public void onReceiveHeaders(Map<String, String> headers)
                                throws ConnectionRefusalException {

                        }
                    }))
            .build(new ChannelApplicationLayer(executorService, null)).get().get();
    timer[n % timer.length].scheduleAtFixedRate(new TimerTask() {
        private NoOpCallable callable = new NoOpCallable();
        long start = System.currentTimeMillis();
        int times = 0;

        @Override
        public void run() {
            try {
                long start = System.currentTimeMillis();
                clientChannel.call(callable);
                times++;
                if (times % 1000 == 0) {
                    System.out
                            .println(String.format("  %s has run %d No-op callables. Rate %.1f/s expect %.1f/s",
                                    clientChannel.getName(), times,
                                    times * 1000.0 / (System.currentTimeMillis() - this.start),
                                    1000.0 / clientIntervalMs));
                }
                long duration = System.currentTimeMillis() - start;
                if (duration > 250L) {
                    System.err.println(String.format("  %s took %dms to complete a callable",
                            clientChannel.getName(), duration));
                }
            } catch (Exception e) {
                e.printStackTrace(System.err);
                IOUtils.closeQuietly(clientChannel);
                cancel();
            }
        }
    }, entropy.nextInt(clientIntervalMs), clientIntervalMs);
}

From source file:edu.umass.cs.nio.MessageExtractor.java

private void processMessageInternal(SocketChannel socket, ByteBuffer incoming) throws IOException {
    /* The emulated delay value is in the message, so we need to read all
     * bytes off incoming and stringify right away. */
    long delay = -1;
    if (JSONDelayEmulator.isDelayEmulated()) {
        byte[] msg = new byte[incoming.remaining()];
        incoming.get(msg);//  w w w .  j av a 2  s  . c o m
        String message = new String(msg, MessageNIOTransport.NIO_CHARSET_ENCODING);
        // always true because of max(0,delay)
        if ((delay = Math.max(0, JSONDelayEmulator.getEmulatedDelay(message))) >= 0)
            // run in a separate thread after scheduled delay
            executor.schedule(new MessageWorker(socket, msg, packetDemuxes), delay, TimeUnit.MILLISECONDS);
    } else
        // run it immediately
        this.demultiplexMessage(new NIOHeader((InetSocketAddress) socket.getRemoteAddress(),
                (InetSocketAddress) socket.getLocalAddress()), incoming);
}

From source file:org.openhab.binding.irtrans.handler.EthernetBridgeHandler.java

protected void onWritable(ByteBuffer buffer) {
    lock.lock();/*from   w  ww  .j  av a  2  s .  com*/
    try {
        synchronized (selector) {
            try {
                selector.selectNow();
            } catch (IOException e) {
                logger.error("An exception occurred while selecting: {}", e.getMessage());
            }
        }

        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey selKey = it.next();
            it.remove();
            if (selKey.isValid() && selKey.isWritable()) {
                SocketChannel aSocketChannel = (SocketChannel) selKey.channel();

                if (aSocketChannel.equals(socketChannel)) {
                    boolean error = false;

                    buffer.rewind();
                    try {
                        logger.trace("Sending '{}' on the channel '{}'->'{}'", new String(buffer.array()),
                                aSocketChannel.getLocalAddress(), aSocketChannel.getRemoteAddress());
                        aSocketChannel.write(buffer);
                    } catch (NotYetConnectedException e) {
                        logger.warn("The channel '{}' is not yet connected: {}", aSocketChannel,
                                e.getMessage());
                        if (!aSocketChannel.isConnectionPending()) {
                            error = true;
                        }
                    } catch (ClosedChannelException e) {
                        // If some other I/O error occurs
                        logger.warn("The channel for '{}' is closed: {}", aSocketChannel, e.getMessage());
                        error = true;
                    } catch (IOException e) {
                        // If some other I/O error occurs
                        logger.warn("An IO exception occured on channel '{}': {}", aSocketChannel,
                                e.getMessage());
                        error = true;
                    }

                    if (error) {
                        try {
                            aSocketChannel.close();
                        } catch (IOException e) {
                            logger.warn("An exception occurred while closing the channel '{}': {}",
                                    aSocketChannel, e.getMessage());
                        }
                    }
                }
            }
        }
    } finally {
        lock.unlock();
    }
}