Package java.nio.channels

Examples of java.nio.channels.DatagramChannel


public class BlockingGetClient {

    public static void main(String[] args) {
        try {
            DatagramChannel channel = DatagramChannel.open();

            InetSocketAddress target = new InetSocketAddress("127.0.0.1", 5683);

            channel.connect(target);

            System.err.println(channel);

            CoapEncoder encoder = new CoapEncoder();
            CoapDecoder decoder = new CoapDecoder();
            ByteBuffer buff = ByteBuffer.allocateDirect(2048);

            Random r = new Random();
            byte[] url = "nlp".getBytes();
            CoapMessage msg = new CoapMessage(1, MessageType.CONFIRMABLE, CoapCode.GET.getCode(), 1234, null,
                    new CoapOption[] { new CoapOption(CoapOptionType.URI_PATH, url) }, null);

            for (int j = 0; j < 8; j++) {
                long start = System.currentTimeMillis();
                final int count = 100000;
                for (int i = 0; i < count; i++) {
                    buff.position(0);
                    buff.limit(buff.capacity());
                    int id = r.nextInt(1024);
                    msg.setId(id);
                    int bytes = channel.send(encoder.encode(msg, null), target);

                    if (bytes < 1) {
                        System.err.println("write fail :/ " + bytes);
                    } else {
                        buff.position(0);
                        buff.limit(buff.capacity());
                        SocketAddress addy = channel.receive(buff);
                        buff.flip();
                        CoapMessage response = decoder.decode(buff, null);
                        if (response.getId() != id) {
                            System.err.println("gni?");
                        }
View Full Code Here


     */
    @Override
    public IoFuture<IoSession> connect(SocketAddress remoteAddress) {
        Assert.assertNotNull(remoteAddress, "remoteAddress");

        DatagramChannel ch;
        try {
            ch = DatagramChannel.open();
        } catch (IOException e) {
            throw new MinaRuntimeException("can't create a new socket, out of file descriptors ?", e);
        }
        try {
            ch.configureBlocking(false);
        } catch (IOException e) {
            throw new MinaRuntimeException("can't configure socket as non-blocking", e);
        }

        UdpSessionConfig config = getSessionConfig();

        NioSelectorLoop loop = (NioSelectorLoop) readWriteSelectorPool.getSelectorLoop();

        NioUdpSession session = new NioUdpSession(this, idleChecker, ch, null, remoteAddress, loop);

        session.setConnected();

        // apply idle configuration
        session.getConfig().setIdleTimeInMillis(IdleStatus.READ_IDLE, config.getIdleTimeInMillis(IdleStatus.READ_IDLE));
        session.getConfig().setIdleTimeInMillis(IdleStatus.WRITE_IDLE,
                config.getIdleTimeInMillis(IdleStatus.WRITE_IDLE));

        // Manage the Idle status
        idleChecker.sessionRead(session, System.currentTimeMillis());
        idleChecker.sessionWritten(session, System.currentTimeMillis());

        // apply the default service socket configuration

        Boolean reuseAddress = config.isReuseAddress();

        if (reuseAddress != null) {
            session.getConfig().setReuseAddress(reuseAddress);
        }

        Integer readBufferSize = config.getReadBufferSize();

        if (readBufferSize != null) {
            session.getConfig().setReadBufferSize(readBufferSize);
        } else {
            int rcvBufferSize;
            try {
                rcvBufferSize = ch.socket().getReceiveBufferSize();
                session.getConfig().setReadBufferSize(rcvBufferSize);

            } catch (SocketException e) {
                throw new MinaRuntimeException("can't configure socket receive buffer size", e);
            }
        }

        Integer sendBufferSize = config.getSendBufferSize();

        if (sendBufferSize != null) {
            session.getConfig().setSendBufferSize(sendBufferSize);
        } else {
            int sndBufferSize;
            try {
                sndBufferSize = ch.socket().getSendBufferSize();
                session.getConfig().setSendBufferSize(sndBufferSize);
            } catch (SocketException e) {
                throw new MinaRuntimeException("can't configure socket send buffe size", e);
            }
        }
View Full Code Here

        if (config == null) {
            config = getDefaultConfig();
        }

        DatagramChannel ch = null;
        boolean initialized = false;
        try {
            ch = DatagramChannel.open();
            DatagramSessionConfig cfg;
            if (config.getSessionConfig() instanceof DatagramSessionConfig) {
                cfg = (DatagramSessionConfig) config.getSessionConfig();
            } else {
                cfg = getDefaultConfig().getSessionConfig();
            }

            ch.socket().setReuseAddress(cfg.isReuseAddress());
            ch.socket().setBroadcast(cfg.isBroadcast());
            ch.socket().setReceiveBufferSize(cfg.getReceiveBufferSize());
            ch.socket().setSendBufferSize(cfg.getSendBufferSize());

            if (ch.socket().getTrafficClass() != cfg.getTrafficClass()) {
                ch.socket().setTrafficClass(cfg.getTrafficClass());
            }

            if (localAddress != null) {
                ch.socket().bind(localAddress);
            }
            ch.connect(address);
            ch.configureBlocking(false);
            initialized = true;
        } catch (IOException e) {
            return DefaultConnectFuture.newFailedFuture(e);
        } finally {
            if (!initialized && ch != null) {
                try {
                    ch.disconnect();
                    ch.close();
                } catch (IOException e) {
                    ExceptionMonitor.getInstance().exceptionCaught(e);
                }
            }
        }

        RegistrationRequest request = new RegistrationRequest(ch, handler,
                config);
        try {
            startupWorker();
        } catch (IOException e) {
            try {
                ch.disconnect();
                ch.close();
            } catch (IOException e2) {
                ExceptionMonitor.getInstance().exceptionCaught(e2);
            }

            return DefaultConnectFuture.newFailedFuture(e);
View Full Code Here

            }
        }
    }

    private void flush(DatagramSessionImpl session) throws IOException {
        DatagramChannel ch = session.getChannel();

        Queue<WriteRequest> writeRequestQueue = session.getWriteRequestQueue();

        for (;;) {
            WriteRequest req = writeRequestQueue.peek();

            if (req == null)
                break;

            ByteBuffer buf = (ByteBuffer) req.getMessage();
            if (buf.remaining() == 0) {
                // pop and fire event
                writeRequestQueue.poll();

                session.increaseWrittenMessages();
                buf.reset();
                session.getFilterChain().fireMessageSent(session, req);
                continue;
            }

            SelectionKey key = session.getSelectionKey();
            if (key == null) {
                scheduleFlush(session);
                break;
            }
            if (!key.isValid()) {
                continue;
            }

            int writtenBytes = ch.write(buf.buf());

            if (writtenBytes == 0) {
                // Kernel buffer is full
                key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
            } else if (writtenBytes > 0) {
View Full Code Here

            if (session == null)
                break;
            else {
                SelectionKey key = session.getSelectionKey();
                DatagramChannel ch = (DatagramChannel) key.channel();
                try {
                    ch.disconnect();
                    ch.close();
                } catch (IOException e) {
                    ExceptionMonitor.getInstance().exceptionCaught(e);
                }

                getListeners().fireSessionDestroyed(session);
View Full Code Here

        if (localAddress == null) {
            throw new NullPointerException("localAddress");
        }

        Selector selector = this.selector;
        DatagramChannel ch = channels.get(localAddress);
        if (selector == null || ch == null) {
            throw new IllegalArgumentException("Unknown localAddress: "
                    + localAddress);
        }

        SelectionKey key = ch.keyFor(selector);
        if (key == null) {
            throw new IllegalArgumentException("Unknown localAddress: "
                    + localAddress);
        }
View Full Code Here

        Iterator<SelectionKey> it = keys.iterator();
        while (it.hasNext()) {
            SelectionKey key = it.next();
            it.remove();

            DatagramChannel ch = (DatagramChannel) key.channel();

            RegistrationRequest req = (RegistrationRequest) key.attachment();
            try {
                if (key.isReadable()) {
                    readSession(ch, req);
View Full Code Here

            }
        }
    }

    private void flush(DatagramSessionImpl session) throws IOException {
        DatagramChannel ch = session.getChannel();

        Queue<WriteRequest> writeRequestQueue = session.getWriteRequestQueue();

        for (;;) {
            WriteRequest req = writeRequestQueue.peek();

            if (req == null)
                break;

            ByteBuffer buf = (ByteBuffer) req.getMessage();
            if (buf.remaining() == 0) {
                // pop and fire event
                writeRequestQueue.poll();

                session.increaseWrittenMessages();
                buf.reset();
                session.getFilterChain().fireMessageSent(session, req);
                continue;
            }

            SelectionKey key = session.getSelectionKey();
            if (key == null) {
                scheduleFlush(session);
                break;
            }
            if (!key.isValid()) {
                continue;
            }

            SocketAddress destination = req.getDestination();
            if (destination == null) {
                destination = session.getRemoteAddress();
            }

            int writtenBytes = ch.send(buf.buf(), destination);

            if (writtenBytes == 0) {
                // Kernel buffer is full
                key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
            } else if (writtenBytes > 0) {
View Full Code Here

            RegistrationRequest req = registerQueue.poll();

            if (req == null)
                break;

            DatagramChannel ch = null;
            try {
                ch = DatagramChannel.open();
                DatagramSessionConfig cfg;
                if (req.config.getSessionConfig() instanceof DatagramSessionConfig) {
                    cfg = (DatagramSessionConfig) req.config.getSessionConfig();
                } else {
                    cfg = getDefaultConfig().getSessionConfig();
                }

                ch.socket().setReuseAddress(cfg.isReuseAddress());
                ch.socket().setBroadcast(cfg.isBroadcast());
                ch.socket().setReceiveBufferSize(cfg.getReceiveBufferSize());
                ch.socket().setSendBufferSize(cfg.getSendBufferSize());

                if (ch.socket().getTrafficClass() != cfg.getTrafficClass()) {
                    ch.socket().setTrafficClass(cfg.getTrafficClass());
                }

                ch.configureBlocking(false);
                ch.socket().bind(req.address);
                if (req.address == null || req.address.getPort() == 0) {
                    req.address = (InetSocketAddress) ch.socket()
                            .getLocalSocketAddress();
                }
                ch.register(selector, SelectionKey.OP_READ, req);
                channels.put(req.address, ch);

                getListeners().fireServiceActivated(this, req.address,
                        req.handler, req.config);
            } catch (Throwable t) {
                req.exception = t;
            } finally {
                synchronized (req) {
                    req.done = true;
                    req.notify();
                }

                if (ch != null && req.exception != null) {
                    try {
                        ch.disconnect();
                        ch.close();
                    } catch (Throwable e) {
                        ExceptionMonitor.getInstance().exceptionCaught(e);
                    }
                }
            }
View Full Code Here

            if (request == null) {
                break;
            }

            DatagramChannel ch = channels.remove(request.address);

            // close the channel
            try {
                if (ch == null) {
                    request.exception = new IllegalArgumentException(
                            "Address not bound: " + request.address);
                } else {
                    SelectionKey key = ch.keyFor(selector);
                    request.registrationRequest = (RegistrationRequest) key
                            .attachment();
                    key.cancel();
                    selector.wakeup(); // wake up again to trigger thread death
                    ch.disconnect();
                    ch.close();
                }
            } catch (Throwable t) {
                ExceptionMonitor.getInstance().exceptionCaught(t);
            } finally {
                synchronized (request) {
View Full Code Here

TOP

Related Classes of java.nio.channels.DatagramChannel

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.