Search in sources :

Example 91 with DatagramChannel

use of java.nio.channels.DatagramChannel in project tomcat by apache.

the class NioReplicationTask method drainChannel.

/**
 * The actual code which drains the channel associated with
 * the given key.  This method assumes the key has been
 * modified prior to invocation to turn off selection
 * interest in OP_READ.  When this method completes it
 * re-enables OP_READ and calls wakeup() on the selector
 * so the selector will resume watching this channel.
 * @param key The key to process
 * @param reader The reader
 * @throws Exception IO error
 */
protected void drainChannel(final SelectionKey key, ObjectReader reader) throws Exception {
    reader.access();
    ReadableByteChannel channel = (ReadableByteChannel) key.channel();
    int count = -1;
    // make buffer empty
    buffer.clear();
    SocketAddress saddr = null;
    if (channel instanceof SocketChannel) {
        // loop while data available, channel is non-blocking
        while ((count = channel.read(buffer)) > 0) {
            // make buffer readable
            buffer.flip();
            if (buffer.hasArray()) {
                reader.append(buffer.array(), 0, count, false);
            } else {
                reader.append(buffer, count, false);
            }
            // make buffer empty
            buffer.clear();
            // do we have at least one package?
            if (reader.hasPackage()) {
                break;
            }
        }
    } else if (channel instanceof DatagramChannel) {
        DatagramChannel dchannel = (DatagramChannel) channel;
        saddr = dchannel.receive(buffer);
        // make buffer readable
        buffer.flip();
        if (buffer.hasArray()) {
            reader.append(buffer.array(), 0, buffer.limit() - buffer.position(), false);
        } else {
            reader.append(buffer, buffer.limit() - buffer.position(), false);
        }
        // make buffer empty
        buffer.clear();
        // did we get a package
        count = reader.hasPackage() ? 1 : -1;
    }
    int pkgcnt = reader.count();
    if (count < 0 && pkgcnt == 0) {
        // end of stream, and no more packages to process
        remoteEof(key);
        return;
    }
    ChannelMessage[] msgs = pkgcnt == 0 ? ChannelData.EMPTY_DATA_ARRAY : reader.execute();
    // register to read new data, before we send it off to avoid dead locks
    registerForRead(key, reader);
    for (ChannelMessage msg : msgs) {
        /**
         * Use send ack here if you want to ack the request to the remote
         * server before completing the request
         * This is considered an asynchronous request
         */
        if (ChannelData.sendAckAsync(msg.getOptions())) {
            sendAck(key, (WritableByteChannel) channel, Constants.ACK_COMMAND, saddr);
        }
        try {
            if (Logs.MESSAGES.isTraceEnabled()) {
                try {
                    Logs.MESSAGES.trace("NioReplicationThread - Received msg:" + new UniqueId(msg.getUniqueId()) + " at " + new java.sql.Timestamp(System.currentTimeMillis()));
                } catch (Throwable t) {
                }
            }
            // process the message
            getCallback().messageDataReceived(msg);
            /**
             * Use send ack here if you want the request to complete on this
             * server before sending the ack to the remote server
             * This is considered a synchronized request
             */
            if (ChannelData.sendAckSync(msg.getOptions())) {
                sendAck(key, (WritableByteChannel) channel, Constants.ACK_COMMAND, saddr);
            }
        } catch (RemoteProcessException e) {
            if (log.isDebugEnabled()) {
                log.error(sm.getString("nioReplicationTask.process.clusterMsg.failed"), e);
            }
            if (ChannelData.sendAckSync(msg.getOptions())) {
                sendAck(key, (WritableByteChannel) channel, Constants.FAIL_ACK_COMMAND, saddr);
            }
        } catch (Exception e) {
            log.error(sm.getString("nioReplicationTask.process.clusterMsg.failed"), e);
            if (ChannelData.sendAckSync(msg.getOptions())) {
                sendAck(key, (WritableByteChannel) channel, Constants.FAIL_ACK_COMMAND, saddr);
            }
        }
        if (getUseBufferPool()) {
            BufferPool.getBufferPool().returnBuffer(msg.getMessage());
            msg.setMessage(null);
        }
    }
    if (count < 0) {
        remoteEof(key);
    }
}
Also used : ReadableByteChannel(java.nio.channels.ReadableByteChannel) SocketChannel(java.nio.channels.SocketChannel) UniqueId(org.apache.catalina.tribes.UniqueId) DatagramChannel(java.nio.channels.DatagramChannel) WritableByteChannel(java.nio.channels.WritableByteChannel) RemoteProcessException(org.apache.catalina.tribes.RemoteProcessException) CancelledKeyException(java.nio.channels.CancelledKeyException) IOException(java.io.IOException) ChannelMessage(org.apache.catalina.tribes.ChannelMessage) RemoteProcessException(org.apache.catalina.tribes.RemoteProcessException) SocketAddress(java.net.SocketAddress)

Example 92 with DatagramChannel

use of java.nio.channels.DatagramChannel in project tomcat by apache.

the class NioReplicationTask method run.

// loop forever waiting for work to do
@Override
public synchronized void run() {
    if (buffer == null) {
        int size = getRxBufSize();
        if (key.channel() instanceof DatagramChannel) {
            size = ChannelReceiver.MAX_UDP_SIZE;
        }
        if ((getOptions() & OPTION_DIRECT_BUFFER) == OPTION_DIRECT_BUFFER) {
            buffer = ByteBuffer.allocateDirect(size);
        } else {
            buffer = ByteBuffer.allocate(size);
        }
    } else {
        buffer.clear();
    }
    if (key == null) {
        // just in case
        return;
    }
    if (log.isTraceEnabled()) {
        log.trace("Servicing key:" + key);
    }
    try {
        ObjectReader reader = (ObjectReader) key.attachment();
        if (reader == null) {
            if (log.isTraceEnabled()) {
                log.trace("No object reader, cancelling:" + key);
            }
            cancelKey(key);
        } else {
            if (log.isTraceEnabled()) {
                log.trace("Draining channel:" + key);
            }
            drainChannel(key, reader);
        }
    } catch (Exception e) {
        // end expire after a certain time.
        if (e instanceof CancelledKeyException) {
        // do nothing
        } else if (e instanceof IOException) {
            // don't spew out stack traces for IO exceptions unless debug is enabled.
            if (log.isDebugEnabled()) {
                log.debug("IOException in replication worker, unable to drain channel. Probable cause: Keep alive socket closed[" + e.getMessage() + "].", e);
            } else {
                log.warn(sm.getString("nioReplicationTask.unable.drainChannel.ioe", e.getMessage()));
            }
        } else if (log.isErrorEnabled()) {
            // this is a real error, log it.
            log.error(sm.getString("nioReplicationTask.exception.drainChannel"), e);
        }
        cancelKey(key);
    }
    key = null;
    // done, ready for more, return to pool
    getTaskPool().returnWorker(this);
}
Also used : CancelledKeyException(java.nio.channels.CancelledKeyException) DatagramChannel(java.nio.channels.DatagramChannel) ObjectReader(org.apache.catalina.tribes.io.ObjectReader) IOException(java.io.IOException) RemoteProcessException(org.apache.catalina.tribes.RemoteProcessException) CancelledKeyException(java.nio.channels.CancelledKeyException) IOException(java.io.IOException)

Example 93 with DatagramChannel

use of java.nio.channels.DatagramChannel in project Smartcity-Smarthouse by TechnionYP5777.

the class Sensor method getSystemIp.

private InetAddress getSystemIp() throws IOException, SocketException, InterruptedException {
    try (DatagramChannel channel = DatagramChannel.open()) {
        channel.configureBlocking(false);
        // zero means the
        channel.socket().bind(new InetSocketAddress(0));
        // port
        // number is
        // chosen
        // dynamically
        channel.socket().setBroadcast(true);
        final ByteBuffer buf = ByteBuffer.allocate(8);
        buf.clear();
        SocketAddress serverAddress;
        do {
            channel.send(buf, new InetSocketAddress("255.255.255.255", systemPort));
            Thread.sleep(1000);
            // see if got answer
            serverAddress = channel.receive(buf);
        } while (serverAddress == null);
        return ((InetSocketAddress) serverAddress).getAddress();
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) DatagramChannel(java.nio.channels.DatagramChannel) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) ByteBuffer(java.nio.ByteBuffer)

Example 94 with DatagramChannel

use of java.nio.channels.DatagramChannel in project Aeron by real-logic.

the class SelectorAndTransportTest method shouldSetSocketBufferSizesFromUdpChannelForReceiveChannel.

@Test
void shouldSetSocketBufferSizesFromUdpChannelForReceiveChannel() throws IOException {
    final DatagramChannel spyChannel = spy(DatagramChannel.open(StandardProtocolFamily.INET));
    final UdpChannel channel = UdpChannel.parse("aeron:udp?endpoint=localhost:" + RCV_PORT + "|so-sndbuf=8k|so-rcvbuf=4k");
    receiveChannelEndpoint = new ReceiveChannelEndpoint(channel, mockDispatcher, mockReceiveStatusIndicator, context);
    try (MockedStatic<DatagramChannel> mockDatagramChannel = Mockito.mockStatic(DatagramChannel.class)) {
        mockDatagramChannel.when(() -> DatagramChannel.open(StandardProtocolFamily.INET)).thenReturn(spyChannel);
        receiveChannelEndpoint.openDatagramChannel(mockReceiveStatusIndicator);
        verify(spyChannel).setOption(StandardSocketOptions.SO_SNDBUF, 8192);
        verify(spyChannel).setOption(StandardSocketOptions.SO_RCVBUF, 4096);
    }
}
Also used : DatagramChannel(java.nio.channels.DatagramChannel) Test(org.junit.jupiter.api.Test)

Example 95 with DatagramChannel

use of java.nio.channels.DatagramChannel in project Aeron by real-logic.

the class SelectorAndTransportTest method shouldSetSocketBufferSizesFromUdpChannelForSendChannel.

@Test
void shouldSetSocketBufferSizesFromUdpChannelForSendChannel() throws IOException {
    final DatagramChannel spyChannel = spy(DatagramChannel.open(StandardProtocolFamily.INET));
    final UdpChannel channel = UdpChannel.parse("aeron:udp?endpoint=localhost:" + RCV_PORT + "|so-sndbuf=8k|so-rcvbuf=4k");
    sendChannelEndpoint = new SendChannelEndpoint(channel, mockReceiveStatusIndicator, context);
    try (MockedStatic<DatagramChannel> mockDatagramChannel = Mockito.mockStatic(DatagramChannel.class)) {
        mockDatagramChannel.when(() -> DatagramChannel.open(StandardProtocolFamily.INET)).thenReturn(spyChannel);
        sendChannelEndpoint.openDatagramChannel(mockReceiveStatusIndicator);
        verify(spyChannel).setOption(StandardSocketOptions.SO_SNDBUF, 8192);
        verify(spyChannel).setOption(StandardSocketOptions.SO_RCVBUF, 4096);
    }
}
Also used : DatagramChannel(java.nio.channels.DatagramChannel) Test(org.junit.jupiter.api.Test)

Aggregations

DatagramChannel (java.nio.channels.DatagramChannel)211 InetSocketAddress (java.net.InetSocketAddress)91 ByteBuffer (java.nio.ByteBuffer)71 IOException (java.io.IOException)57 DatagramSocket (java.net.DatagramSocket)21 SocketAddress (java.net.SocketAddress)21 MembershipKey (java.nio.channels.MembershipKey)21 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)20 SocketChannel (java.nio.channels.SocketChannel)17 SelectionKey (java.nio.channels.SelectionKey)16 InetAddress (java.net.InetAddress)13 Selector (java.nio.channels.Selector)13 Test (org.junit.Test)11 SocketException (java.net.SocketException)9 ClosedChannelException (java.nio.channels.ClosedChannelException)9 Histogram (org.HdrHistogram.Histogram)8 CancelledKeyException (java.nio.channels.CancelledKeyException)7 DatagramPacket (java.net.DatagramPacket)5 NetworkInterface (java.net.NetworkInterface)5 ArrayList (java.util.ArrayList)5