Example usage for java.nio.channels DatagramChannel open

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

Introduction

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

Prototype

public static DatagramChannel open() throws IOException 

Source Link

Document

Opens a datagram channel.

Usage

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

public synchronized void start() throws IOException {
    if (!__isStarted) {
        __isStarted = true;/*from ww  w.  j av a 2s.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:com.offbynull.portmapper.natpmp.NatPmpController.java

/**
 * Constructs a {@link NatPmpController} object.
 * @param gatewayAddress address of router/gateway
 * @param listener a listener to listen for all NAT-PMP packets from this router
 * @throws NullPointerException if any argument is {@code null}
 * @throws IOException if problems initializing UDP channels
 *//*from  w ww  . jav  a2  s . co  m*/
public NatPmpController(InetAddress gatewayAddress, final NatPmpControllerListener listener)
        throws IOException {
    Validate.notNull(gatewayAddress);

    this.gateway = new InetSocketAddress(gatewayAddress, 5351);

    List<DatagramChannel> channels = new ArrayList<>(3);

    try {
        unicastChannel = DatagramChannel.open();
        unicastChannel.configureBlocking(false);
        unicastChannel.socket().bind(new InetSocketAddress(0));

        ipv4MulticastChannel = DatagramChannel.open(StandardProtocolFamily.INET);
        ipv4MulticastChannel.configureBlocking(false);
        ipv4MulticastChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        ipv4MulticastChannel.socket().bind(new InetSocketAddress(5350));
        NetworkUtils.multicastListenOnAllIpv4InterfaceAddresses(ipv4MulticastChannel);

        ipv6MulticastChannel = DatagramChannel.open(StandardProtocolFamily.INET6);
        ipv6MulticastChannel.configureBlocking(false);
        ipv6MulticastChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        ipv6MulticastChannel.socket().bind(new InetSocketAddress(5350));
        NetworkUtils.multicastListenOnAllIpv6InterfaceAddresses(ipv6MulticastChannel);
    } catch (IOException ioe) {
        IOUtils.closeQuietly(unicastChannel);
        IOUtils.closeQuietly(ipv4MulticastChannel);
        IOUtils.closeQuietly(ipv6MulticastChannel);
        throw ioe;
    }

    channels.add(unicastChannel);
    channels.add(ipv4MulticastChannel);
    channels.add(ipv6MulticastChannel);

    this.communicator = new UdpCommunicator(channels);
    this.communicator.startAsync().awaitRunning();

    if (listener != null) {
        this.communicator.addListener(new UdpCommunicatorListener() {

            @Override
            public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel,
                    ByteBuffer packet) {
                CommunicationType type;
                if (channel == unicastChannel) {
                    type = CommunicationType.UNICAST;
                } else if (channel == ipv4MulticastChannel || channel == ipv6MulticastChannel) {
                    type = CommunicationType.MULTICAST;
                } else {
                    return; // unknown, do nothing
                }

                try {
                    packet.mark();
                    listener.incomingResponse(type, new ExternalAddressNatPmpResponse(packet));
                } catch (BufferUnderflowException | IllegalArgumentException e) { // NOPMD
                    // ignore
                } finally {
                    packet.reset();
                }

                try {
                    packet.mark();
                    listener.incomingResponse(type, new UdpMappingNatPmpResponse(packet));
                } catch (BufferUnderflowException | IllegalArgumentException e) { // NOPMD
                    // ignore
                } finally {
                    packet.reset();
                }

                try {
                    packet.mark();
                    listener.incomingResponse(type, new TcpMappingNatPmpResponse(packet));
                } catch (BufferUnderflowException | IllegalArgumentException e) { // NOPMD
                    // ignore
                } finally {
                    packet.reset();
                }
            }
        });
    }
}

From source file:com.robonobo.eon.EONManager.java

public EONManager(String instanceName, ScheduledThreadPoolExecutor executor, InetSocketAddress localEP)
        throws EONException {
    this.instanceName = instanceName;
    log = getLogger(getClass());/*from  w  ww.j a va 2 s.c  o m*/
    debugLogging = log.isDebugEnabled();
    this.executor = executor;
    try {
        chan = DatagramChannel.open();
        chan.socket().setReceiveBufferSize(SOCKET_BUFFER_SIZE);
        chan.socket().setSendBufferSize(SOCKET_BUFFER_SIZE);
        chan.socket().bind(localEP);
        // Re-grab the value to see what we ended up on
        this.localEP = (InetSocketAddress) chan.socket().getLocalSocketAddress();
    } catch (IOException e) {
        throw new EONException("Unable to construct udp socket on " + localEP.toString(), e);
    }
    sockOK = true;
    pktSender = new PktSender(chan);
    recvThread = null;
    conns = new ConnectionHolder(this);
    mod = new Modulo((long) Integer.MAX_VALUE + 1);
    log.debug("EONManager created on endpoint " + this.localEP.getAddress().getHostAddress() + ":"
            + this.localEP.getPort());
}

From source file:org.apache.nifi.processor.util.listen.dispatcher.DatagramChannelDispatcher.java

@Override
public void open(final InetAddress nicAddress, final int port, final int maxBufferSize) throws IOException {
    stopped = false;//from   w w w. ja  va2  s .  c  o m
    datagramChannel = DatagramChannel.open();
    datagramChannel.configureBlocking(false);

    if (maxBufferSize > 0) {
        datagramChannel.setOption(StandardSocketOptions.SO_RCVBUF, maxBufferSize);
        final int actualReceiveBufSize = datagramChannel.getOption(StandardSocketOptions.SO_RCVBUF);
        if (actualReceiveBufSize < maxBufferSize) {
            logger.warn("Attempted to set Socket Buffer Size to " + maxBufferSize
                    + " bytes but could only set to " + actualReceiveBufSize
                    + "bytes. You may want to consider changing the Operating System's "
                    + "maximum receive buffer");
        }
    }

    // we don't have to worry about nicAddress being null here because InetSocketAddress already handles it
    datagramChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    datagramChannel.socket().bind(new InetSocketAddress(nicAddress, port));

    // if a sending host and port were provided then connect to that specific address to only receive
    // datagrams from that host/port, otherwise we can receive datagrams from any host/port
    if (sendingHost != null && sendingPort != null) {
        datagramChannel.connect(new InetSocketAddress(sendingHost, sendingPort));
    }

    selector = Selector.open();
    datagramChannel.register(selector, SelectionKey.OP_READ);
}

From source file:com.offbynull.portmapper.pcp.PcpController.java

/**
 * Constructs a {@link PcpController} object.
 * @param random used to generate nonce values for requests
 * @param gatewayAddress address of router/gateway
 * @param selfAddress address of this machine on the interface that can talk to the router/gateway
 * @param listener a listener to listen for all PCP packets from this router
 * @throws NullPointerException if any argument is {@code null}
 * @throws IOException if problems initializing UDP channels
 */// www .  j a  va2  s .  co  m
public PcpController(Random random, InetAddress gatewayAddress, InetAddress selfAddress,
        final PcpControllerListener listener) throws IOException {
    Validate.notNull(random);
    Validate.notNull(gatewayAddress);
    Validate.notNull(selfAddress);

    this.gateway = new InetSocketAddress(gatewayAddress, 5351);

    List<DatagramChannel> channels = new ArrayList<>(3);

    try {
        unicastChannel = DatagramChannel.open();
        unicastChannel.configureBlocking(false);
        unicastChannel.socket().bind(new InetSocketAddress(0));

        ipv4MulticastChannel = DatagramChannel.open(StandardProtocolFamily.INET);
        ipv4MulticastChannel.configureBlocking(false);
        ipv4MulticastChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        ipv4MulticastChannel.socket().bind(new InetSocketAddress(5350));
        NetworkUtils.multicastListenOnAllIpv4InterfaceAddresses(ipv4MulticastChannel);

        ipv6MulticastChannel = DatagramChannel.open(StandardProtocolFamily.INET6);
        ipv6MulticastChannel.configureBlocking(false);
        ipv6MulticastChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        ipv6MulticastChannel.socket().bind(new InetSocketAddress(5350));
        NetworkUtils.multicastListenOnAllIpv6InterfaceAddresses(ipv6MulticastChannel);
    } catch (IOException ioe) {
        IOUtils.closeQuietly(unicastChannel);
        IOUtils.closeQuietly(ipv4MulticastChannel);
        IOUtils.closeQuietly(ipv6MulticastChannel);
        throw ioe;
    }

    channels.add(unicastChannel);
    channels.add(ipv4MulticastChannel);
    channels.add(ipv6MulticastChannel);

    this.communicator = new UdpCommunicator(channels);
    this.selfAddress = selfAddress;
    this.random = random;

    this.communicator.startAsync().awaitRunning();

    if (listener != null) {
        this.communicator.addListener(new UdpCommunicatorListener() {

            @Override
            public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel,
                    ByteBuffer packet) {
                CommunicationType type;
                if (channel == unicastChannel) {
                    type = CommunicationType.UNICAST;
                } else if (channel == ipv4MulticastChannel || channel == ipv6MulticastChannel) {
                    type = CommunicationType.MULTICAST;
                } else {
                    return; // unknown, do nothing
                }

                try {
                    packet.mark();
                    listener.incomingResponse(type, new AnnouncePcpResponse(packet));
                } catch (BufferUnderflowException | IllegalArgumentException e) { // NOPMD
                    // ignore
                } finally {
                    packet.reset();
                }

                try {
                    packet.mark();
                    listener.incomingResponse(type, new MapPcpResponse(packet));
                } catch (BufferUnderflowException | IllegalArgumentException e) { // NOPMD
                    // ignore
                } finally {
                    packet.reset();
                }

                try {
                    packet.mark();
                    listener.incomingResponse(type, new PeerPcpResponse(packet));
                } catch (BufferUnderflowException | IllegalArgumentException e) { // NOPMD
                    // ignore
                } finally {
                    packet.reset();
                }
            }
        });
    }
}

From source file:net.sf.jinsim.UDPChannel.java

/**
 * Construct a Receiver that is ready to communicate with a LFS server at a particular address.
 * /*  www  .  jav  a  2 s. c om*/
 * @param channel
 *            The DatagramChannel that the communication will take place on.
 * @param address
 *            A network address to send acknowledgement (ACK) packets to.
 * @param multicast
 *            Receiver will relay the packets received to a multicast address if multicast is true.
 * @throws IOException
 */
public UDPChannel(InetSocketAddress address, boolean multicast) throws IOException {
    super();

    datagramChannel = DatagramChannel.open();
    datagramChannel.configureBlocking(false);
    datagramChannel.socket().bind(null);
    //datagramChannel.connect(address);
    this.address = address;

    if (multicast) {
        InetAddress group = InetAddress.getByName("223.223.223.223");
        multicastSocket = new MulticastSocket();
        multicastSocket.joinGroup(group);
    }

}

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.
 * /*w  ww  .j av a  2 s  . 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);
        }
    });
}

From source file:org.restcomm.sbc.media.MediaZone.java

public void setLocalProxy(String proxyHost) throws UnknownHostException, SocketException {
    this.proxyHost = proxyHost;

    proxyAddress = new InetSocketAddress(proxyHost, proxyPort);

    try {/* ww w  .  ja v a 2 s.co m*/
        channel = DatagramChannel.open();
        channel.bind(proxyAddress);
    } catch (IOException e) {
        throw new SocketException(e.getMessage());
    }

    socket = channel.socket();

    if (LOG.isTraceEnabled()) {
        LOG.trace("Opened socket " + proxyAddress.toString() + " for " + this.toPrint());
    }

    if (!canMux) {
        rtcpProxyAddress = new InetSocketAddress(proxyHost, proxyPort + 1);

        try {
            rtcpChannel = DatagramChannel.open();
            rtcpChannel.bind(rtcpProxyAddress);
        } catch (IOException e) {
            throw new SocketException(e.getMessage());
        }

        rtcpSocket = rtcpChannel.socket();

        if (LOG.isTraceEnabled()) {
            LOG.trace("Opened socket " + rtcpProxyAddress.toString() + " for " + this.toPrint());
        }
    }

}

From source file:com.packetsender.android.PacketListenerService.java

@Override
protected void onHandleIntent(Intent intent) {

    dataStore = new DataStorage(getSharedPreferences(DataStorage.PREFS_SETTINGS_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_SAVEDPACKETS_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_SERVICELOG_NAME, 0),
            getSharedPreferences(DataStorage.PREFS_MAINTRAFFICLOG_NAME, 0));

    listenportTCP = dataStore.getTCPPort();
    listenportUDP = dataStore.getUDPPort();
    Log.i("service", DataStorage.FILE_LINE("TCP: " + listenportTCP + " / UDP: " + listenportUDP));

    Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);

    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);

    startNotification();//from ww  w . jav a 2  s.  c o m

    CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder();
    ByteBuffer response = null;
    try {
        response = encoder.encode(CharBuffer.wrap("response"));
    } catch (CharacterCodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {

        SocketAddress localportTCP = new InetSocketAddress(listenportTCP);
        SocketAddress localportUDP = new InetSocketAddress(listenportUDP);

        tcpserver = ServerSocketChannel.open();
        tcpserver.socket().bind(localportTCP);

        udpserver = DatagramChannel.open();
        udpserver.socket().bind(localportUDP);

        tcpserver.configureBlocking(false);
        udpserver.configureBlocking(false);

        Selector selector = Selector.open();

        tcpserver.register(selector, SelectionKey.OP_ACCEPT);
        udpserver.register(selector, SelectionKey.OP_READ);

        ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);
        receiveBuffer.clear();

        shutdownListener = new Runnable() {
            public void run() {

                if (false) {

                    try {
                        tcpserver.close();
                    } catch (IOException e) {
                    }
                    try {
                        udpserver.close();
                    } catch (IOException e) {
                    }
                    stopSelf();
                } else {
                    mHandler.postDelayed(shutdownListener, 2000);

                }

            }
        };

        sendListener = new Runnable() {
            public void run() {

                //Packet fetchedPacket = mDbHelper.needSendPacket();
                Packet[] fetchedPackets = dataStore.fetchAllServicePackets();

                if (fetchedPackets.length > 0) {
                    dataStore.clearServicePackets();
                    Log.d("service",
                            DataStorage.FILE_LINE("sendListener found " + fetchedPackets.length + " packets"));

                    for (int i = 0; i < fetchedPackets.length; i++) {
                        Packet fetchedPacket = fetchedPackets[i];
                        Log.d("service", DataStorage.FILE_LINE("send packet " + fetchedPacket.toString()));

                    }

                    new SendPacketsTask().execute(fetchedPackets);
                }

                mHandler.postDelayed(sendListener, 2000);

            }
        };

        //start shutdown listener
        mHandler.postDelayed(shutdownListener, 2000);

        //start send listener
        mHandler.postDelayed(sendListener, 5000);

        while (true) {
            try { // Handle per-connection problems below
                  // Wait for a client to connect
                Log.d("service", DataStorage.FILE_LINE("waiting for connection"));
                selector.select();
                Log.d("service", DataStorage.FILE_LINE("client connection"));

                Set keys = selector.selectedKeys();

                for (Iterator i = keys.iterator(); i.hasNext();) {

                    SelectionKey key = (SelectionKey) i.next();
                    i.remove();

                    Channel c = (Channel) key.channel();

                    if (key.isAcceptable() && c == tcpserver) {

                        SocketChannel client = tcpserver.accept();

                        if (client != null) {

                            Socket tcpSocket = client.socket();
                            packetCounter++;

                            DataInputStream in = new DataInputStream(tcpSocket.getInputStream());

                            byte[] buffer = new byte[1024];
                            int received = in.read(buffer);
                            byte[] bufferConvert = new byte[received];
                            System.arraycopy(buffer, 0, bufferConvert, 0, bufferConvert.length);

                            Packet storepacket = new Packet();
                            storepacket.tcpOrUdp = "TCP";
                            storepacket.fromIP = tcpSocket.getInetAddress().getHostAddress();

                            storepacket.toIP = "You";
                            storepacket.fromPort = tcpSocket.getPort();
                            storepacket.port = tcpSocket.getLocalPort();
                            storepacket.data = bufferConvert;

                            UpdateNotification("TCP:" + storepacket.toAscii(), "From " + storepacket.fromIP);

                            Log.i("service", DataStorage.FILE_LINE("Got TCP"));
                            //dataStore.SavePacket(storepacket);

                            /*
                            Intent tcpIntent = new Intent();
                            tcpIntent.setAction(ResponseReceiver.ACTION_RESP);
                            tcpIntent.addCategory(Intent.CATEGORY_DEFAULT);
                            tcpIntent.putExtra(PARAM_OUT_MSG, storepacket.name);
                            sendBroadcast(tcpIntent);
                            */

                            storepacket.nowMe();
                            dataStore.saveTrafficPacket(storepacket);
                            Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            if (false) //mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).equalsIgnoreCase("Yes"))
                            {
                                storepacket = new Packet();
                                storepacket.name = dataStore.currentTimeStamp();
                                ;
                                storepacket.tcpOrUdp = "TCP";
                                storepacket.fromIP = "You";
                                storepacket.toIP = tcpSocket.getInetAddress().getHostAddress();
                                storepacket.fromPort = tcpSocket.getLocalPort();
                                storepacket.port = tcpSocket.getPort();
                                // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT));

                                storepacket.nowMe();
                                dataStore.saveTrafficPacket(storepacket);
                                Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                                client.write(response); // send response
                            }

                            client.close(); // close connection
                        }
                    } else if (key.isReadable() && c == udpserver) {

                        DatagramSocket udpSocket;
                        DatagramPacket udpPacket;

                        byte[] buffer = new byte[2048];
                        // Create a packet to receive data into the buffer
                        udpPacket = new DatagramPacket(buffer, buffer.length);

                        udpSocket = udpserver.socket();

                        receiveBuffer.clear();

                        InetSocketAddress clientAddress = (InetSocketAddress) udpserver.receive(receiveBuffer);

                        if (clientAddress != null) {

                            String fromAddress = clientAddress.getAddress().getHostAddress();

                            packetCounter++;

                            int received = receiveBuffer.position();
                            byte[] bufferConvert = new byte[received];

                            System.arraycopy(receiveBuffer.array(), 0, bufferConvert, 0, bufferConvert.length);

                            Packet storepacket = new Packet();
                            storepacket.tcpOrUdp = "UDP";
                            storepacket.fromIP = clientAddress.getAddress().getHostAddress();

                            storepacket.toIP = "You";
                            storepacket.fromPort = clientAddress.getPort();
                            storepacket.port = udpSocket.getLocalPort();
                            storepacket.data = bufferConvert;

                            UpdateNotification("UDP:" + storepacket.toAscii(), "From " + storepacket.fromIP);

                            //dataStore.SavePacket(storepacket);
                            storepacket.nowMe();
                            dataStore.saveTrafficPacket(storepacket);
                            Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            if (false)//mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).trim().equalsIgnoreCase("Yes"))
                            {
                                storepacket = new Packet();
                                storepacket.name = dataStore.currentTimeStamp();
                                ;
                                storepacket.tcpOrUdp = "UDP";
                                storepacket.fromIP = "You";
                                storepacket.toIP = clientAddress.getAddress().getHostAddress();
                                storepacket.fromPort = udpSocket.getLocalPort();
                                storepacket.port = clientAddress.getPort();
                                // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT));

                                //dataStore.SavePacket(storepacket);
                                udpserver.send(response, clientAddress);
                                storepacket.nowMe();
                                dataStore.saveTrafficPacket(storepacket);
                                Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));

                            }
                        }
                    }
                }
            } catch (java.io.IOException e) {
                Log.i("service", DataStorage.FILE_LINE("IOException "));
            } catch (Exception e) {
                Log.w("service", DataStorage.FILE_LINE("Fatal Error: " + Log.getStackTraceString(e)));
            }
        }
    } catch (BindException e) {

        //mDbHelper.putServiceError("Error binding to port");
        dataStore.putToast("Port already in use.");
        Log.w("service", DataStorage.FILE_LINE("Bind Exception: " + Log.getStackTraceString(e)));

    } catch (Exception e) {
        //mDbHelper.putServiceError("Fatal Error starting service");
        Log.w("service", DataStorage.FILE_LINE("Startup error: " + Log.getStackTraceString(e)));
    }

    stopNotification();

}

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 w  w .  java2  s .  c  o  m*/
 * @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());
}