Search in sources :

Example 86 with DatagramChannel

use of java.nio.channels.DatagramChannel in project j2objc by google.

the class DatagramChannelTest method testInitialState.

public void testInitialState() throws Exception {
    DatagramChannel dc = DatagramChannel.open();
    try {
        DatagramSocket socket = dc.socket();
        assertFalse(socket.isBound());
        assertFalse(socket.getBroadcast());
        assertFalse(socket.isClosed());
        assertFalse(socket.isConnected());
        assertEquals(0, socket.getLocalPort());
        assertTrue(socket.getLocalAddress().isAnyLocalAddress());
        assertNull(socket.getLocalSocketAddress());
        assertNull(socket.getInetAddress());
        assertEquals(-1, socket.getPort());
        assertNull(socket.getRemoteSocketAddress());
        assertFalse(socket.getReuseAddress());
        assertSame(dc, socket.getChannel());
    } finally {
        dc.close();
    }
}
Also used : DatagramSocket(java.net.DatagramSocket) DatagramChannel(java.nio.channels.DatagramChannel)

Example 87 with DatagramChannel

use of java.nio.channels.DatagramChannel in project j2objc by google.

the class InheritedChannel method createChannel.

/*
     * If standard inherited channel is connected to a socket then return a Channel
     * of the appropriate type based standard input.
     */
private static Channel createChannel() throws IOException {
    // dup the file descriptor - we do this so that for two reasons :-
    // 1. Avoids any timing issues with FileDescriptor.in being closed
    // or redirected while we create the channel.
    // 2. Allows streams based on file descriptor 0 to co-exist with
    // the channel (closing one doesn't impact the other)
    int fdVal = dup(0);
    // Examine the file descriptor - if it's not a socket then we don't
    // create a channel so we release the file descriptor.
    int st;
    st = soType0(fdVal);
    if (st != SOCK_STREAM && st != SOCK_DGRAM) {
        close0(fdVal);
        return null;
    }
    // Next we create a FileDescriptor for the dup'ed file descriptor
    // Have to use reflection and also make assumption on how FD
    // is implemented.
    Class[] paramTypes = { int.class };
    Constructor ctr = Reflect.lookupConstructor("java.io.FileDescriptor", paramTypes);
    Object[] args = { new Integer(fdVal) };
    FileDescriptor fd = (FileDescriptor) Reflect.invoke(ctr, args);
    // Now create the channel. If the socket is a streams socket then
    // we see if tthere is a peer (ie: connected). If so, then we
    // create a SocketChannel, otherwise a ServerSocketChannel.
    // If the socket is a datagram socket then create a DatagramChannel
    SelectorProvider provider = SelectorProvider.provider();
    assert provider instanceof sun.nio.ch.SelectorProviderImpl;
    Channel c;
    if (st == SOCK_STREAM) {
        InetAddress ia = peerAddress0(fdVal);
        if (ia == null) {
            c = new InheritedServerSocketChannelImpl(provider, fd);
        } else {
            int port = peerPort0(fdVal);
            assert port > 0;
            InetSocketAddress isa = new InetSocketAddress(ia, port);
            c = new InheritedSocketChannelImpl(provider, fd, isa);
        }
    } else {
        c = new InheritedDatagramChannelImpl(provider, fd);
    }
    return c;
}
Also used : Constructor(java.lang.reflect.Constructor) InetSocketAddress(java.net.InetSocketAddress) SocketChannel(java.nio.channels.SocketChannel) DatagramChannel(java.nio.channels.DatagramChannel) Channel(java.nio.channels.Channel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) FileDescriptor(java.io.FileDescriptor) SelectorProvider(java.nio.channels.spi.SelectorProvider) InetAddress(java.net.InetAddress)

Example 88 with DatagramChannel

use of java.nio.channels.DatagramChannel in project robo4j by Robo4J.

the class ReadDatagramSelectionKeyHandler method handle.

// TODO: 2/25/18 (miro) -> Datagram type -> not only string is possible
@Override
public SelectionKey handle() {
    final DatagramChannel channel = (DatagramChannel) key.channel();
    try {
        ByteBuffer buffer = serverContext.getPropertySafe(ByteBuffer.class, PROPERTY_BYTE_BUFFER);
        buffer.clear();
        channel.receive(buffer);
        buffer.flip();
        String message = ChannelBufferUtils.byteBufferToString(buffer);
        final String[] headerAndBody = message.split(HTTP_HEADER_BODY_DELIMITER);
        final String firstLine = RoboHttpUtils.correctLine(headerAndBody[0]);
        final String[] tokens = firstLine.split(HttpConstant.HTTP_EMPTY_SEP);
        final String body = headerAndBody[1];
        final ServerPathConfig serverPathConfig = serverContext.getPathConfig(new PathHttpMethod(tokens[1], null));
        final RoboReference<Object> roboReference = serverPathConfig.getRoboUnit();
        final SocketDecoder<Object, Object> decoder = codecRegistry.getDecoder(roboReference.getMessageType());
        final Object decodedMessage = decoder.decode(body);
        serverPathConfig.getRoboUnit().sendMessage(decodedMessage);
        final DatagramResponseProcess responseProcess = new DatagramResponseProcess(tokens[1], roboReference, decodedMessage);
        outBuffers.put(key, responseProcess);
        return key;
    } catch (IOException e) {
        throw new SocketException("hanlde", e);
    }
}
Also used : SocketException(com.robo4j.socket.http.SocketException) ServerPathConfig(com.robo4j.socket.http.units.ServerPathConfig) DatagramChannel(java.nio.channels.DatagramChannel) DatagramResponseProcess(com.robo4j.socket.http.request.DatagramResponseProcess) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) PathHttpMethod(com.robo4j.socket.http.units.PathHttpMethod)

Example 89 with DatagramChannel

use of java.nio.channels.DatagramChannel in project robo4j by Robo4J.

the class ChannelUtils method initDatagramChannel.

public static DatagramChannel initDatagramChannel(DatagramConnectionType connectionType, SocketContext<?> context) {
    try {
        final DatagramChannel result = DatagramChannel.open();
        SocketAddress address = getSocketAddressByContext(context);
        switch(connectionType) {
            case SERVER:
                DatagramSocket socket = result.socket();
                result.configureBlocking(false);
                socket.bind(address);
                break;
            case CLIENT:
                result.connect(address);
                break;
            default:
                throw new SocketException("int not supported: " + connectionType);
        }
        return result;
    } catch (Exception e) {
        SimpleLoggingUtil.error(ChannelUtils.class, "init datagram socket channel", e);
        throw new SocketException("init datagram socket channel", e);
    }
}
Also used : SocketException(com.robo4j.socket.http.SocketException) DatagramSocket(java.net.DatagramSocket) DatagramChannel(java.nio.channels.DatagramChannel) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) SocketException(com.robo4j.socket.http.SocketException) IOException(java.io.IOException)

Example 90 with DatagramChannel

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

the class NioReceiver method cancelledKey.

public static void cancelledKey(SelectionKey key) {
    ObjectReader reader = (ObjectReader) key.attachment();
    if (reader != null) {
        reader.setCancelled(true);
        reader.finish();
    }
    key.cancel();
    key.attach(null);
    if (key.channel() instanceof SocketChannel) {
        try {
            ((SocketChannel) key.channel()).socket().close();
        } catch (IOException e) {
            if (log.isDebugEnabled()) {
                log.debug("", e);
            }
        }
    }
    if (key.channel() instanceof DatagramChannel) {
        try {
            ((DatagramChannel) key.channel()).socket().close();
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.debug("", e);
            }
        }
    }
    try {
        key.channel().close();
    } catch (IOException e) {
        if (log.isDebugEnabled()) {
            log.debug("", e);
        }
    }
}
Also used : ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketChannel(java.nio.channels.SocketChannel) DatagramChannel(java.nio.channels.DatagramChannel) ObjectReader(org.apache.catalina.tribes.io.ObjectReader) IOException(java.io.IOException) CancelledKeyException(java.nio.channels.CancelledKeyException) IOException(java.io.IOException) ClosedSelectorException(java.nio.channels.ClosedSelectorException)

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