Search in sources :

Example 51 with SelectionKey

use of java.nio.channels.SelectionKey in project netty by netty.

the class OioSctpChannel method doConnect.

@Override
protected void doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception {
    if (localAddress != null) {
        ch.bind(localAddress);
    }
    boolean success = false;
    try {
        ch.connect(remoteAddress);
        boolean finishConnect = false;
        while (!finishConnect) {
            if (connectSelector.select(SO_TIMEOUT) >= 0) {
                final Set<SelectionKey> selectionKeys = connectSelector.selectedKeys();
                for (SelectionKey key : selectionKeys) {
                    if (key.isConnectable()) {
                        selectionKeys.clear();
                        finishConnect = true;
                        break;
                    }
                }
                selectionKeys.clear();
            }
        }
        success = ch.finishConnect();
    } finally {
        if (!success) {
            doClose();
        }
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey)

Example 52 with SelectionKey

use of java.nio.channels.SelectionKey in project netty by netty.

the class OioSctpChannel method doWrite.

@Override
protected void doWrite(ChannelOutboundBuffer in) throws Exception {
    if (!writeSelector.isOpen()) {
        return;
    }
    final int size = in.size();
    final int selectedKeys = writeSelector.select(SO_TIMEOUT);
    if (selectedKeys > 0) {
        final Set<SelectionKey> writableKeys = writeSelector.selectedKeys();
        if (writableKeys.isEmpty()) {
            return;
        }
        Iterator<SelectionKey> writableKeysIt = writableKeys.iterator();
        int written = 0;
        for (; ; ) {
            if (written == size) {
                // all written
                return;
            }
            writableKeysIt.next();
            writableKeysIt.remove();
            SctpMessage packet = (SctpMessage) in.current();
            if (packet == null) {
                return;
            }
            ByteBuf data = packet.content();
            int dataLen = data.readableBytes();
            ByteBuffer nioData;
            if (data.nioBufferCount() != -1) {
                nioData = data.nioBuffer();
            } else {
                nioData = ByteBuffer.allocate(dataLen);
                data.getBytes(data.readerIndex(), nioData);
                nioData.flip();
            }
            final MessageInfo mi = MessageInfo.createOutgoing(association(), null, packet.streamIdentifier());
            mi.payloadProtocolID(packet.protocolIdentifier());
            mi.streamNumber(packet.streamIdentifier());
            mi.unordered(packet.isUnordered());
            ch.send(nioData, mi);
            written++;
            in.remove();
            if (!writableKeysIt.hasNext()) {
                return;
            }
        }
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) ByteBuf(io.netty.buffer.ByteBuf) SctpMessage(io.netty.channel.sctp.SctpMessage) ByteBuffer(java.nio.ByteBuffer) MessageInfo(com.sun.nio.sctp.MessageInfo)

Example 53 with SelectionKey

use of java.nio.channels.SelectionKey in project netty by netty.

the class OioSctpServerChannel method doReadMessages.

@Override
protected int doReadMessages(List<Object> buf) throws Exception {
    if (!isActive()) {
        return -1;
    }
    SctpChannel s = null;
    int acceptedChannels = 0;
    try {
        final int selectedKeys = selector.select(SO_TIMEOUT);
        if (selectedKeys > 0) {
            final Iterator<SelectionKey> selectionKeys = selector.selectedKeys().iterator();
            for (; ; ) {
                SelectionKey key = selectionKeys.next();
                selectionKeys.remove();
                if (key.isAcceptable()) {
                    s = sch.accept();
                    if (s != null) {
                        buf.add(new OioSctpChannel(this, s));
                        acceptedChannels++;
                    }
                }
                if (!selectionKeys.hasNext()) {
                    return acceptedChannels;
                }
            }
        }
    } catch (Throwable t) {
        logger.warn("Failed to create a new channel from an accepted sctp channel.", t);
        if (s != null) {
            try {
                s.close();
            } catch (Throwable t2) {
                logger.warn("Failed to close a sctp channel.", t2);
            }
        }
    }
    return acceptedChannels;
}
Also used : SctpChannel(com.sun.nio.sctp.SctpChannel) SelectionKey(java.nio.channels.SelectionKey)

Example 54 with SelectionKey

use of java.nio.channels.SelectionKey in project openhab1-addons by openhab.

the class CULNetworkHandlerImpl method processSelectedKeys.

private void processSelectedKeys(Set<SelectionKey> keys) throws Exception {
    Iterator<SelectionKey> itr = keys.iterator();
    while (itr.hasNext()) {
        SelectionKey key = itr.next();
        if (key.isReadable()) {
            processRead(key);
        }
        if (key.isWritable()) {
            processWrite(key);
        }
        if (key.isConnectable()) {
            processConnect(key);
        }
        if (key.isAcceptable()) {
            ;
        }
        itr.remove();
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey)

Example 55 with SelectionKey

use of java.nio.channels.SelectionKey in project openhab1-addons by openhab.

the class CULNetworkHandlerImpl method send.

private void send(ByteBuffer buffer) throws InterruptedException, IOException {
    if (!connected.get()) {
        throw new IOException("not connected");
    }
    synchronized (writeBuf) {
        // try direct write of what's in the buffer to free up space
        if (writeBuf.remaining() < buffer.remaining()) {
            writeBuf.flip();
            int bytesOp = 0, bytesTotal = 0;
            while (writeBuf.hasRemaining() && (bytesOp = channel.write(writeBuf)) > 0) {
                bytesTotal += bytesOp;
            }
            writeBuf.compact();
            logger.debug("Written {} bytes to the network", bytesTotal);
        }
        // if didn't help, wait till some space appears
        if (Thread.currentThread().getId() != thread.getId()) {
            while (writeBuf.remaining() < buffer.remaining()) {
                writeBuf.wait();
            }
        } else {
            if (writeBuf.remaining() < buffer.remaining()) {
                // TODO: add reallocation or buffers chain
                throw new IOException("send buffer full");
            }
        }
        writeBuf.put(buffer);
        // try direct write to decrease the latency
        writeBuf.flip();
        int bytesOp = 0, bytesTotal = 0;
        while (writeBuf.hasRemaining() && (bytesOp = channel.write(writeBuf)) > 0) {
            bytesTotal += bytesOp;
        }
        writeBuf.compact();
        logger.debug("Written {} bytes to the network", bytesTotal);
        if (writeBuf.hasRemaining()) {
            SelectionKey key = channel.keyFor(selector);
            key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
            selector.wakeup();
        }
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) IOException(java.io.IOException)

Aggregations

SelectionKey (java.nio.channels.SelectionKey)202 IOException (java.io.IOException)93 SocketChannel (java.nio.channels.SocketChannel)59 Selector (java.nio.channels.Selector)44 ServerSocketChannel (java.nio.channels.ServerSocketChannel)41 ClosedChannelException (java.nio.channels.ClosedChannelException)30 InetSocketAddress (java.net.InetSocketAddress)27 CancelledKeyException (java.nio.channels.CancelledKeyException)25 ByteBuffer (java.nio.ByteBuffer)24 ClosedSelectorException (java.nio.channels.ClosedSelectorException)17 SelectableChannel (java.nio.channels.SelectableChannel)13 Test (org.junit.Test)13 Iterator (java.util.Iterator)9 Socket (java.net.Socket)7 ArrayList (java.util.ArrayList)7 SocketTimeoutException (java.net.SocketTimeoutException)6 AbstractSelectionKey (java.nio.channels.spi.AbstractSelectionKey)6 EOFException (java.io.EOFException)5 DatagramChannel (java.nio.channels.DatagramChannel)5 HashSet (java.util.HashSet)5