Example usage for java.nio.channels DatagramChannel socket

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

Introduction

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

Prototype

public abstract DatagramSocket socket();

Source Link

Document

Retrieves a datagram socket associated with this channel.

Usage

From source file:net.ymate.platform.serv.nio.datagram.NioUdpServer.java

public synchronized void start() throws IOException {
    if (!__isStarted) {
        __isStarted = true;//from  w  w  w.j  a v a2 s . c  o  m
        __eventGroup = new NioEventGroup<NioUdpListener>(__serverCfg, __listener, __codec) {
            @Override
            protected SelectableChannel __doChannelCreate(INioServerCfg cfg) throws IOException {
                DatagramChannel _channel = DatagramChannel.open();
                _channel.configureBlocking(false);
                _channel.socket().bind(new InetSocketAddress(cfg.getServerHost(), cfg.getPort()));
                return _channel;
            }

            @Override
            protected String __doBuildProcessorName() {
                return StringUtils.capitalize(name()).concat("UdpServer-NioEventProcessor-");
            }

            @Override
            protected void __doInitProcessors() throws IOException {
                __processors = new NioEventProcessor[__selectorCount];
                for (int _idx = 0; _idx < __selectorCount; _idx++) {
                    __processors[_idx] = new NioEventProcessor<NioUdpListener>(this,
                            __doBuildProcessorName() + _idx) {
                        @Override
                        protected void __doExceptionEvent(SelectionKey key, final Throwable e) {
                            final INioSession _session = (INioSession) key.attachment();
                            if (_session != null) {
                                __eventGroup.executorService().submit(new Runnable() {
                                    public void run() {
                                        try {
                                            __eventGroup.listener().onExceptionCaught(e, _session);
                                        } catch (Throwable ex) {
                                            _LOG.error(e.getMessage(), RuntimeUtils.unwrapThrow(ex));
                                        }
                                    }
                                });
                            } else {
                                _LOG.error(e.getMessage(), RuntimeUtils.unwrapThrow(e));
                            }
                        }
                    };
                    __processors[_idx].start();
                }
            }

            @Override
            protected void __doRegisterEvent() throws IOException {
                for (NioEventProcessor _processor : __processors) {
                    _processor.registerEvent(__channel, SelectionKey.OP_READ,
                            new NioSession<NioUdpListener>(this, __channel) {
                                @Override
                                protected int __doChannelRead(ByteBuffer buffer) throws IOException {
                                    SocketAddress _address = ((DatagramChannel) __channel).receive(buffer);
                                    if (_address != null) {
                                        attr(SocketAddress.class.getName(), _address);
                                        return __buffer.remaining();
                                    }
                                    return 0;
                                }

                                @Override
                                protected int __doChannelWrite(ByteBuffer buffer) throws IOException {
                                    SocketAddress _address = attr(SocketAddress.class.getName());
                                    if (_address != null) {
                                        return ((DatagramChannel) __channel).send(buffer, _address);
                                    }
                                    buffer.reset();
                                    return 0;
                                }
                            });
                }
            }
        };
        __eventGroup.start();
        //
        _LOG.info("UdpServer [" + __eventGroup.name() + "] started at " + __serverCfg.getServerHost() + ":"
                + __serverCfg.getPort());
    }
}

From source file:org.apache.axis2.transport.udp.IODispatcher.java

/**
 * Add a new endpoint. This method creates a new socket listening on
 * the UDP port specified in the endpoint description and makes sure
 * that incoming packets are routed to the specified service.
 * //  w ww .  j a  v a 2s . c om
 * @param endpoint the endpoint description
 * @throws IOException if the socket could not be created or
 *         registered with the selector
 */
public void addEndpoint(final Endpoint endpoint) throws IOException {
    final DatagramChannel channel = DatagramChannel.open();
    channel.socket().bind(new InetSocketAddress(endpoint.getPort()));
    channel.configureBlocking(false);
    execute(new SelectorOperation() {
        @Override
        public void doExecute(Selector selector) throws IOException {
            channel.register(selector, SelectionKey.OP_READ, endpoint);
        }
    });
    log.info("UDP endpoint started on port : " + endpoint.getPort());
}

From source file:org.apache.synapse.transport.udp.IODispatcher.java

/**
 * Add a new endpoint. This method creates a new socket listening on
 * the UDP port specified in the endpoint description and makes sure
 * that incoming packets are routed to the specified service.
 * //from   ww w.  j a v a 2  s . com
 * @param endpoint the endpoint description
 * @throws IOException if the socket could not be created or
 *         registered with the selector
 */
public void addEndpoint(final Endpoint endpoint) throws IOException {
    final DatagramChannel channel = DatagramChannel.open();
    channel.socket().bind(new InetSocketAddress(endpoint.getPort()));
    channel.configureBlocking(false);
    execute(new SelectorOperation() {
        @Override
        public void doExecute(Selector selector) throws IOException {
            channel.register(selector, SelectionKey.OP_READ, endpoint);
        }
    });
}

From source file:org.sipfoundry.sipxbridge.symmitron.DataShuffler.java

/**
 * Sit in a loop running the following algorthim till exit:
 * /* w ww . j  av a 2  s  .c o  m*/
 * <pre>
 * Let Si be a Sym belonging to Bridge B where an inbound packet P is received
 * Increment received packet count for B.
 * Record time for the received packet.
 * Record inboundAddress from where the packet was received
 * send(B,chan,inboundAddress)
 *            
 * </pre>
 * 
 */
public void run() {

    // Wait for an event one of the registered channels
    logger.debug("Starting Shuffler");

    while (true) {
        Bridge bridge = null;
        try {

            if (initializeSelectors.get()) {
                initializeSelector();
            }

            selector.select();

            while (!workQueue.isEmpty()) {
                logger.debug("Got a work item");
                WorkItem workItem = (WorkItem) workQueue.remove(0);
                workItem.doWork();
            }

            // Iterate over the set of keys for which events are
            // available
            Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();
            while (selectedKeys.hasNext()) {
                SelectionKey key = (SelectionKey) selectedKeys.next();
                // The key must be removed or you can get one way audio ( i.e. will read a
                // null byte ).
                // (see issue 2075 ).
                selectedKeys.remove();
                if (!key.isValid()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Discarding packet:Key not valid");
                    }

                    continue;
                }
                if (key.isReadable()) {
                    readBuffer.clear();
                    DatagramChannel datagramChannel = (DatagramChannel) key.channel();
                    if (!datagramChannel.isOpen()) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("DataShuffler: Datagram channel is closed -- discarding packet.");
                        }
                        continue;
                    }
                    bridge = ConcurrentSet.getBridge(datagramChannel);
                    if (bridge == null) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("DataShuffler: Discarding packet: Could not find bridge");
                        }
                        continue;
                    }
                    Sym packetReceivedSym = bridge.getReceiverSym(datagramChannel);
                    /*
                     * Note the original hold value and put the transmitter on which this packet was received on hold.
                     */
                    if (packetReceivedSym == null || packetReceivedSym.getTransmitter() == null) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(
                                    "DataShuffler: Could not find sym for inbound channel -- discarding packet");
                        }
                        continue;
                    }
                    boolean holdValue = packetReceivedSym.getTransmitter().isOnHold();
                    packetReceivedSym.getTransmitter().setOnHold(true);

                    InetSocketAddress remoteAddress = (InetSocketAddress) datagramChannel.receive(readBuffer);

                    bridge.pakcetsReceived++;
                    if (bridge.getState() != BridgeState.RUNNING) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(
                                    "DataShuffler: Discarding packet: Bridge state is " + bridge.getState());
                        }
                        packetReceivedSym.getTransmitter().setOnHold(holdValue);
                        continue;
                    }
                    if (logger.isTraceEnabled()) {
                        logger.trace("got something on " + datagramChannel.socket().getLocalPort());
                    }

                    long stamp = getPacketCounter();
                    send(bridge, datagramChannel, remoteAddress, stamp, false);
                    /*
                     * Reset the old value.
                     */
                    packetReceivedSym.getTransmitter().setOnHold(holdValue);

                }
            }
        } catch (Exception ex) {
            logger.error("Unexpected exception occured", ex);
            if (bridge != null && bridge.sessions != null) {
                for (Sym rtpSession : bridge.sessions) {
                    rtpSession.close();
                }
            }
            if (bridge != null)
                bridge.setState(BridgeState.TERMINATED);
            continue;
        }

    }

}

From source file:org.sipfoundry.sipxbridge.symmitron.DataShuffler.java

/**
 * //from  w w w.j  a  va  2  s.  co  m
 * Implements the following search algorithm to retrieve a datagram channel that is associated
 * with the far end:
 * 
 * <pre>
 * getSelfRoutedDatagramChannel(farEnd)
 * For each selectable key do:
 *   let ipAddress be the local ip address
 *   let p be the local port
 *   let d be the datagramChannel associated with the key
 *   If  farEnd.ipAddress == ipAddress  &amp;&amp; port == localPort return d
 * return null
 * </pre>
 * 
 * @param farEnd
 * @return
 */

public static DatagramChannel getSelfRoutedDatagramChannel(InetSocketAddress farEnd) {
    // Iterate over the set of keys for which events are
    // available
    InetAddress ipAddress = farEnd.getAddress();
    int port = farEnd.getPort();
    for (Iterator<SelectionKey> selectedKeys = selector.keys().iterator(); selectedKeys.hasNext();) {
        SelectionKey key = selectedKeys.next();
        if (!key.isValid()) {
            continue;
        }
        DatagramChannel datagramChannel = (DatagramChannel) key.channel();
        if (datagramChannel.socket().getLocalAddress().equals(ipAddress)
                && datagramChannel.socket().getLocalPort() == port) {
            return datagramChannel;
        }

    }
    return null;

}

From source file:org.sipfoundry.sipxrelay.DataShuffler.java

/**
 * Sit in a loop running the following algorthim till exit:
 * /*from   ww  w.  j ava 2 s .co  m*/
 * <pre>
 * Let Si be a Sym belonging to Bridge B where an inbound packet P is received
 * Increment received packet count for B.
 * Record time for the received packet.
 * Record inboundAddress from where the packet was received
 * send(B,chan,inboundAddress)
 *            
 * </pre>
 * 
 */
public void run() {

    // Wait for an event one of the registered channels
    logger.debug("Starting Shuffler");

    while (true) {
        Bridge bridge = null;
        try {

            if (initializeSelectors.get()) {
                initializeSelector();
            }

            selector.select();

            checkWorkQueue();

            // Iterate over the set of keys for which events are
            // available
            Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();
            while (selectedKeys.hasNext()) {
                SelectionKey key = (SelectionKey) selectedKeys.next();
                // The key must be removed or you can get one way audio ( i.e. will read a
                // null byte ).
                // (see issue 2075 ).
                selectedKeys.remove();
                if (!key.isValid()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Discarding packet:Key not valid");
                    }

                    continue;
                }
                if (key.isReadable()) {
                    readBuffer.clear();
                    DatagramChannel datagramChannel = (DatagramChannel) key.channel();
                    if (!datagramChannel.isOpen()) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("DataShuffler: Datagram channel is closed -- discarding packet.");
                        }
                        continue;
                    }
                    bridge = ConcurrentSet.getBridge(datagramChannel);
                    if (bridge == null) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("DataShuffler: Discarding packet: Could not find bridge");
                        }
                        continue;
                    }
                    Sym packetReceivedSym = bridge.getReceiverSym(datagramChannel);
                    /*
                     * Note the original hold value and put the transmitter on which this packet was received on hold.
                     */
                    if (packetReceivedSym == null || packetReceivedSym.getTransmitter() == null) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(
                                    "DataShuffler: Could not find sym for inbound channel -- discarding packet");
                        }
                        continue;
                    }
                    boolean holdValue = packetReceivedSym.getTransmitter().isOnHold();
                    packetReceivedSym.getTransmitter().setOnHold(true);

                    InetSocketAddress remoteAddress = (InetSocketAddress) datagramChannel.receive(readBuffer);

                    bridge.pakcetsReceived++;
                    if (bridge.getState() != BridgeState.RUNNING) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(
                                    "DataShuffler: Discarding packet: Bridge state is " + bridge.getState());
                        }
                        packetReceivedSym.getTransmitter().setOnHold(holdValue);
                        continue;
                    }
                    if (logger.isTraceEnabled()) {
                        logger.trace("got something on " + datagramChannel.socket().getLocalPort());
                    }

                    long stamp = getPacketCounter();
                    send(bridge, datagramChannel, remoteAddress, stamp, false);
                    /*
                     * Reset the old value.
                     */
                    packetReceivedSym.getTransmitter().setOnHold(holdValue);

                }
            }
        } catch (Exception ex) {
            logger.error("Unexpected exception occured", ex);
            if (bridge != null && bridge.sessions != null) {
                for (Sym rtpSession : bridge.sessions) {
                    rtpSession.close();
                }
            }
            if (bridge != null)
                bridge.setState(BridgeState.TERMINATED);
            continue;
        }

    }

}