Example usage for java.nio.channels SocketChannel socket

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

Introduction

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

Prototype

public abstract Socket socket();

Source Link

Document

Retrieves a socket associated with this channel.

Usage

From source file:voldemort.common.nio.SelectorManagerWorker.java

public SelectorManagerWorker(Selector selector, SocketChannel socketChannel, int socketBufferSize) {
    this.selector = selector;
    this.socketChannel = socketChannel;
    this.socketBufferSize = socketBufferSize;
    this.resizeThreshold = socketBufferSize * 2; // This is arbitrary...

    this.createTimestamp = System.nanoTime();
    this.isClosed = new AtomicBoolean(false);

    if (logger.isDebugEnabled())
        logger.debug("Accepting remote connection from " + socketChannel.socket());
}

From source file:voldemort.server.niosocket.NioSelectorManager.java

@Override
protected void processEvents() {
    try {/*w  ww  . ja  va 2  s  .  c  o  m*/
        SocketChannel socketChannel = null;

        while ((socketChannel = socketChannelQueue.poll()) != null) {
            if (isClosed.get()) {
                if (logger.isInfoEnabled())
                    logger.debug("Closed, exiting for " + endpoint);

                break;
            }

            try {
                if (logger.isDebugEnabled())
                    logger.debug("Registering connection from " + socketChannel.socket().getPort());

                socketChannel.socket().setTcpNoDelay(true);
                socketChannel.socket().setReuseAddress(true);
                socketChannel.socket().setSendBufferSize(socketBufferSize);

                if (socketChannel.socket().getReceiveBufferSize() != this.socketBufferSize)
                    if (logger.isDebugEnabled())
                        logger.debug("Requested socket receive buffer size was " + this.socketBufferSize
                                + " bytes but actual size is " + socketChannel.socket().getReceiveBufferSize()
                                + " bytes.");

                if (socketChannel.socket().getSendBufferSize() != this.socketBufferSize)
                    if (logger.isDebugEnabled())
                        logger.debug("Requested socket send buffer size was " + this.socketBufferSize
                                + " bytes but actual size is " + socketChannel.socket().getSendBufferSize()
                                + " bytes.");

                socketChannel.configureBlocking(false);
                AsyncRequestHandler attachment = new AsyncRequestHandler(selector, socketChannel,
                        requestHandlerFactory, socketBufferSize, numActiveConnections);

                if (!isClosed.get()) {
                    socketChannel.register(selector, SelectionKey.OP_READ, attachment);
                    numActiveConnections.increment();
                }
            } catch (ClosedSelectorException e) {
                if (logger.isDebugEnabled())
                    logger.debug("Selector is closed, exiting");

                close();

                break;
            } catch (Exception e) {
                if (logger.isEnabledFor(Level.ERROR))
                    logger.error(e.getMessage(), e);
            }
        }
    } catch (Exception e) {
        if (logger.isEnabledFor(Level.ERROR))
            logger.error(e.getMessage(), e);
    }
}

From source file:net.timewalker.ffmq4.transport.tcp.nio.NIOTcpMultiplexer.java

protected boolean finalizeConnect(NIOClientSocketHandler clientHandler, SocketChannel channel,
        Selector selector) {/*from  ww  w  .  j  av  a2  s .c o  m*/
    try {
        // Finish the connection handshake
        channel.finishConnect();

        log.debug("[" + clientHandler.getId() + "] Connected to " + channel.socket().getInetAddress());

        // Unregister connect interest
        removeInterest(channel, SelectionKey.OP_CONNECT, selector);

        return true;
    } catch (SocketException e) {
        log.error("[" + clientHandler.getId() + "] Could not connect to remote server : " + e.getMessage());
        return false;
    } catch (Exception e) {
        log.error("[" + clientHandler.getId() + "] Could not finalize connection", e);
        return false;
    }
}

From source file:eu.stratosphere.nephele.taskmanager.bytebuffered.OutgoingConnection.java

/**
 * Reports an I/O error which occurred while writing data to the TCP connection. As a result of the I/O error the
 * connection is closed and the interest keys are canceled. Moreover, the task which queued the currently
 * transmitted transfer envelope is notified about the error and the current envelope is dropped. If the current
 * envelope contains a buffer, the buffer is freed.
 * <p>//  w ww  . j a  v  a 2s  . c  om
 * This method should only be called by the {@link OutgoingConnectionThread} object.
 * 
 * @param ioe
 *        thrown if an error occurs while reseting the connection
 */
public void reportTransmissionProblem(IOException ioe) {

    final SocketChannel socketChannel = (SocketChannel) this.selectionKey.channel();

    // First, write exception to log
    if (this.currentEnvelope != null) {
        LOG.error("The connection between " + socketChannel.socket().getLocalAddress() + " and "
                + socketChannel.socket().getRemoteSocketAddress()
                + " experienced an IOException for transfer envelope "
                + this.currentEnvelope.getSequenceNumber());
    } else {
        LOG.error("The connection between " + socketChannel.socket().getLocalAddress() + " and "
                + socketChannel.socket().getRemoteSocketAddress() + " experienced an IOException");
    }

    // Close the connection and cancel the interest key
    synchronized (this.queuedEnvelopes) {
        try {
            LOG.debug("Closing connection to " + socketChannel.socket().getRemoteSocketAddress());
            socketChannel.close();
        } catch (IOException e) {
            LOG.debug("An error occurred while responding to an IOException");
            LOG.debug(e);
        }

        this.selectionKey.cancel();

        // Error is fatal
        LOG.error(ioe);

        // Trigger new connection if there are more envelopes to be transmitted
        if (this.queuedEnvelopes.isEmpty()) {
            this.isConnected = false;
            this.isSubscribedToWriteEvent = false;
        } else {
            this.connectionThread.triggerConnect(this);
            this.isConnected = true;
            this.isSubscribedToWriteEvent = true;
        }

        // We must assume the current envelope is corrupted so we notify the task which created it.
        if (this.currentEnvelope != null) {
            if (this.currentEnvelope.getBuffer() != null) {
                this.currentEnvelope.getBuffer().recycleBuffer();
                this.currentEnvelope = null;
            }
        }
    }
}

From source file:ee.ria.xroad.proxy.clientproxy.FastestSocketSelector.java

SocketInfo select() throws IOException {
    log.trace("select()");

    Selector selector = Selector.open();

    SocketInfo selectedSocket = initConnections(selector);
    if (selectedSocket != null) {
        return selectedSocket;
    }//from w ww  . j  av  a2s  .  com

    URI selectedAddress = null;
    SocketChannel channel = null;
    try {
        SelectionKey key = selectFirstConnectedSocketChannel(selector);
        if (key == null) {
            return null;
        }

        channel = (SocketChannel) key.channel();
        selectedAddress = (URI) key.attachment();
    } finally {
        try {
            closeSelector(selector, channel);
        } catch (Exception e) {
            log.error("Error while closing selector", e);
        }
    }

    if (channel != null) {
        channel.configureBlocking(true);
        return new SocketInfo(selectedAddress, channel.socket());
    }

    return null;
}

From source file:com.springrts.springls.Clients.java

/**
 * Will create new <code>Client</code> object, add it to the 'clients' list
 * and register its socket channel with 'readSelector'.
 * @param sendBufferSize specifies the sockets send buffer size.
 *///from  w w  w  . ja  v  a2s . com
public Client addNewClient(SocketChannel chan, Selector readSelector, int sendBufferSize) {
    Client client = new Client(chan);
    client.receiveContext(context);
    clients.add(client);

    // register the channel with the selector
    // store a new Client as the Key's attachment
    try {
        chan.configureBlocking(false);
        chan.socket().setSendBufferSize(sendBufferSize);
        // TODO this doesn't seem to have an effect with java.nio
        //chan.socket().setSoTimeout(TIMEOUT_LENGTH);
        client.setSelKey(chan.register(readSelector, SelectionKey.OP_READ, client));
    } catch (IOException ioex) {
        LOG.warn("Failed to establish a connection with a client", ioex);
        killClient(client, "Failed to establish a connection");
        return null;
    }

    return client;
}

From source file:de.kapsi.net.daap.nio.DaapServerNIO.java

/**
 * Accept an icoming connection//from  w  w  w  . j a v  a 2  s .c  o  m
 * 
 * @throws IOException
 */
private void processAccept(SelectionKey sk) throws IOException {

    if (!sk.isValid())
        return;

    ServerSocketChannel ssc = (ServerSocketChannel) sk.channel();
    SocketChannel channel = ssc.accept();

    if (channel == null)
        return;

    if (channel.isOpen() && accept(channel.socket().getInetAddress())) {

        channel.configureBlocking(false);

        DaapConnection connection = new DaapConnectionNIO(this, channel);

        SelectionKey key = channel.register(selector, SelectionKey.OP_READ, connection);

    } else {
        try {
            channel.close();
        } catch (IOException err) {
            LOG.error("SocketChannel.close()", err);
        }
    }
}

From source file:net.timewalker.ffmq4.transport.tcp.nio.NIOTcpMultiplexer.java

protected boolean acceptClient(NIOServerSocketHandler serverHandler, SocketChannel socketChannel) {
    synchronized (clientHandlers) {
        NIOClientSocketHandler clientHandler = serverHandler.createClientHandler(this, socketChannel);
        if (clientHandler == null)
            return false;

        clientHandlers.put(clientHandler.getId(), clientHandler);
        log.debug("[" + clientHandler.getId() + "] Accepted new client from "
                + socketChannel.socket().getInetAddress().getHostAddress() + " (" + clientHandlers.size()
                + ") : " + clientHandler.getId());
    }//  w  w  w  .ja  v  a 2  s  .c  om
    return true;
}

From source file:org.springframework.integration.ip.tcp.connection.TcpNioConnectionTests.java

@Test
public void testByteArrayReadWithOffset() throws Exception {
    SocketChannel socketChannel = mock(SocketChannel.class);
    Socket socket = mock(Socket.class);
    when(socketChannel.socket()).thenReturn(socket);
    TcpNioConnection connection = new TcpNioConnection(socketChannel, false, false, null, null);
    TcpNioConnection.ChannelInputStream stream = (ChannelInputStream) new DirectFieldAccessor(connection)
            .getPropertyValue("channelInputStream");
    stream.write(ByteBuffer.wrap("foo".getBytes()));
    byte[] out = new byte[5];
    int n = stream.read(out, 1, 4);
    assertEquals(3, n);/* w w  w .ja va2 s . c o  m*/
    assertEquals("\u0000foo\u0000", new String(out));
}

From source file:morphy.service.SocketConnectionService.java

protected void disposeSocketChannel(SocketChannel channel) {
    if (channel.isConnected()) {
        try {/*from  w  w w .j  ava  2  s.com*/
            channel.close();
        } catch (Throwable t) {
        }
    }
    socketToSession.remove(channel.socket());
}