Example usage for java.net DatagramSocket DatagramSocket

List of usage examples for java.net DatagramSocket DatagramSocket

Introduction

In this page you can find the example usage for java.net DatagramSocket DatagramSocket.

Prototype

public DatagramSocket() throws SocketException 

Source Link

Document

Constructs a datagram socket and binds it to any available port on the local host machine.

Usage

From source file:org.apache.nifi.processors.standard.TestListenUDP.java

@Test
public void testDefaultBehavior() throws IOException, InterruptedException {
    final List<String> messages = getMessages(15);
    final int expectedQueued = messages.size();
    final int expectedTransferred = messages.size();

    // default behavior should produce a FlowFile per message sent

    run(new DatagramSocket(), messages, expectedQueued, expectedTransferred);
    runner.assertAllFlowFilesTransferred(ListenUDP.REL_SUCCESS, messages.size());

    List<MockFlowFile> mockFlowFiles = runner.getFlowFilesForRelationship(ListenUDP.REL_SUCCESS);
    verifyFlowFiles(mockFlowFiles);/*  w ww .  j a  v  a  2s  .c  om*/
    verifyProvenance(expectedTransferred);
}

From source file:org.mule.transport.udp.UdpSocketFactory.java

protected DatagramSocket createSocket() throws IOException {
    return new DatagramSocket();
}

From source file:com.iiitd.networking.UDPMessenger.java

/**
 * Sends a broadcast message (TAG EPOCH_TIME message). Opens a new socket in case it's closed.
 * @param message the message to send (multicast). It can't be null or 0-characters long.
 * @return/*from w ww.j a  v  a2s .com*/
 * @throws IllegalArgumentException
 */
public boolean sendMessage(String message) throws IllegalArgumentException {
    if (message == null || message.length() == 0)
        throw new IllegalArgumentException();

    // Check for WiFi connectivity
    ConnectivityManager connManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    if (mWifi == null || !mWifi.isConnected()) {
        Log.d(DEBUG_TAG,
                "Sorry! You need to be in a WiFi network in order to send UDP multicast packets. Aborting.");
        return false;
    }

    // Check for IP address
    WifiManager wim = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    int ip = wim.getConnectionInfo().getIpAddress();

    // Create the send socket
    if (socket == null) {
        try {
            socket = new DatagramSocket();
        } catch (SocketException e) {
            Log.d(DEBUG_TAG, "There was a problem creating the sending socket. Aborting.");
            e.printStackTrace();
            return false;
        }
    }

    // Build the packet
    DatagramPacket packet;
    Message msg = new Message(TAG, message);
    byte data[] = msg.toString().getBytes();

    WifiInfo wifiInfo = wim.getConnectionInfo();
    int ipa = wifiInfo.getIpAddress();
    String ipAddress = Formatter.formatIpAddress(ipa);

    try {
        //         packet = new DatagramPacket(data, data.length, InetAddress.getByName(ipToString(ip, true)), MULTICAST_PORT);
        packet = new DatagramPacket(data, data.length, InetAddress.getByName(ipAddress), MULTICAST_PORT);
    } catch (UnknownHostException e) {
        Log.d(DEBUG_TAG, "It seems that " + ipToString(ip, true) + " is not a valid ip! Aborting.");
        e.printStackTrace();
        return false;
    }

    try {
        socket.send(packet);
    } catch (IOException e) {
        Log.d(DEBUG_TAG, "There was an error sending the UDP packet. Aborted.");
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:org.openhab.io.hueemulation.internal.HueEmulationUpnpServer.java

@Override
public void run() {
    MulticastSocket recvSocket = null;
    // since jupnp shares port 1900, lets use a different port to send UDP packets on just to be safe.
    DatagramSocket sendSocket = null;
    byte[] buf = new byte[1000];
    DatagramPacket recv = new DatagramPacket(buf, buf.length);
    while (running) {
        try {/* w  w  w  . j av a2s .  c  om*/
            if (discoveryIp != null && discoveryIp.trim().length() > 0) {
                address = InetAddress.getByName(discoveryIp);
            } else {
                Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
                while (interfaces.hasMoreElements()) {
                    NetworkInterface ni = interfaces.nextElement();
                    Enumeration<InetAddress> addresses = ni.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress addr = addresses.nextElement();
                        if (addr instanceof Inet4Address && !addr.isLoopbackAddress()) {
                            address = addr;
                            break;
                        }
                    }
                }
            }
            InetSocketAddress socketAddr = new InetSocketAddress(MULTI_ADDR, UPNP_PORT_RECV);
            recvSocket = new MulticastSocket(UPNP_PORT_RECV);
            recvSocket.joinGroup(socketAddr, NetworkInterface.getByInetAddress(address));
            sendSocket = new DatagramSocket();
            while (running) {
                recvSocket.receive(recv);
                if (recv.getLength() > 0) {
                    String data = new String(recv.getData());
                    logger.trace("Got SSDP Discovery packet from {}:{}", recv.getAddress().getHostAddress(),
                            recv.getPort());
                    if (data.startsWith("M-SEARCH")) {
                        String msg = String.format(discoString, "http://" + address.getHostAddress().toString()
                                + ":" + System.getProperty("org.osgi.service.http.port") + discoPath, usn);
                        DatagramPacket response = new DatagramPacket(msg.getBytes(), msg.length(),
                                recv.getAddress(), recv.getPort());
                        try {
                            logger.trace("Sending to {} : {}", recv.getAddress().getHostAddress(), msg);
                            sendSocket.send(response);
                        } catch (IOException e) {
                            logger.error("Could not send UPNP response", e);
                        }
                    }
                }
            }
        } catch (SocketException e) {
            logger.error("Socket error with UPNP server", e);
        } catch (IOException e) {
            logger.error("IO Error with UPNP server", e);
        } finally {
            IOUtils.closeQuietly(recvSocket);
            IOUtils.closeQuietly(sendSocket);
            if (running) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                }
            }
        }
    }
}

From source file:org.apache.hadoop.metrics.ganglia.GangliaContext.java

@InterfaceAudience.Private
public void init(String contextName, ContextFactory factory) {
    super.init(contextName, factory);
    parseAndSetPeriod(PERIOD_PROPERTY);//from   w  w w  .  j a v a 2 s  . co m

    metricsServers = Util.parse(getAttribute(SERVERS_PROPERTY), DEFAULT_PORT);

    unitsTable = getAttributeTable(UNITS_PROPERTY);
    slopeTable = getAttributeTable(SLOPE_PROPERTY);
    tmaxTable = getAttributeTable(TMAX_PROPERTY);
    dmaxTable = getAttributeTable(DMAX_PROPERTY);

    try {
        datagramSocket = new DatagramSocket();
    } catch (SocketException se) {
        se.printStackTrace();
    }
}

From source file:com.navercorp.pinpoint.collector.receiver.thrift.udp.UDPReceiverTest.java

@Test
public void sendSocketBufferSize() throws IOException {
    DatagramPacket datagramPacket = new DatagramPacket(new byte[0], 0, 0);

    DatagramSocket datagramSocket = new DatagramSocket();
    datagramSocket.connect(new InetSocketAddress(ADDRESS, PORT));

    datagramSocket.send(datagramPacket);
    datagramSocket.close();/*w w w  . j a  va  2 s.  co  m*/
}

From source file:org.cloudata.core.common.metrics.GangliaContext.java

/** Creates a new instance of GangliaContext */
public synchronized void startMonitoring() {
    CloudataMetricsFactory factory = CloudataMetricsFactory.getFactory();
    String periodStr = factory.getAttribute(contextName + "." + PERIOD_PROPERTY);
    if (periodStr != null) {
        int period = 0;
        try {/*  w  w  w  .j  a va2 s  . c  o m*/
            period = Integer.parseInt(periodStr);
        } catch (NumberFormatException nfe) {
        }
        if (period <= 0) {
            throw new MetricsException("Invalid period: " + periodStr);
        }
        setPeriod(period);
    }

    metricsServers = parse(factory.getAttribute(contextName + "." + SERVERS_PROPERTY), DEFAULT_PORT);

    unitsTable = getAttributeTable(factory, UNITS_PROPERTY);
    slopeTable = getAttributeTable(factory, SLOPE_PROPERTY);
    tmaxTable = getAttributeTable(factory, TMAX_PROPERTY);
    dmaxTable = getAttributeTable(factory, DMAX_PROPERTY);

    try {
        datagramSocket = new DatagramSocket();
    } catch (SocketException se) {
        se.printStackTrace();
    }

    super.startMonitoring();
}

From source file:com.lfv.yada.net.client.ClientNetworkManager.java

public ClientNetworkManager(int terminalId, ClientBundle bundle, SocketAddress serverSocketAddr,
        SocketAddress localhostBindSocketAddr, SocketAddress multicastSocketAddr, int multicastTTL,
        TerminalProperties properties) throws IOException {

    // Create a logger for this class
    log = LogFactory.getLog(getClass());

    // Load terminal properties
    this.properties = properties;

    // Setup stuff
    this.terminalId = terminalId;
    this.bundle = bundle;
    this.serverSocketAddr = new SocketAddress(serverSocketAddr);

    // Resolve local host address
    InetAddress localHost = getLocalHostFix();
    if (localHost == null) {
        localHost = InetAddress.getLocalHost();
        if (localHost == null)
            throw new UnknownHostException("Could not resolve ip address of localhost");
    }//from   w  w  w. ja v  a  2  s. c om

    // The socket to be used for sending and receiving unicast packets
    DatagramSocket usocket;
    if (localhostBindSocketAddr.getAddress() == 0)
        usocket = new DatagramSocket();
    else
        usocket = new DatagramSocket(localhostBindSocketAddr.getPort(),
                localhostBindSocketAddr.getInetAddress());

    // The multicast socket
    InetAddress maddr = multicastSocketAddr.getInetAddress();
    int mport = multicastSocketAddr.getPort();
    MulticastSocket msocket = null;

    multicastAvailable = (maddr != null && mport > 0);
    if (multicastAvailable) {
        msocket = new MulticastSocket(mport);
        try {
            msocket.joinGroup(maddr);
            msocket.setTimeToLive(multicastTTL);
        } catch (SocketException ex) {
            log.warn("!!!");
            log.warn("!!! Unable to create multicast socket! Multicasting has been disabled!");
            log.warn("!!! On linux systems a default gateway must be defined, try:");
            log.warn("!!! > route add default gw <some_ip_address>");
            log.warn("!!!");
            msocket = null;
            multicastAvailable = false;
        }
    } else
        log.warn("No multicast address or port defined, multicasting has been disabled!");

    // Store the local unicast ip address and port
    localSocketAddr = new SocketAddress(localHost, usocket.getLocalPort());

    // Create a receiver and a sender (send/recv must use the same port number)
    receiver = new ClientPacketReceiver(terminalId, usocket, msocket);
    sender = new ClientPacketSender(usocket, msocket, multicastSocketAddr);

    // Create a transaction mananger
    transactionManager = new TransactionManager(sender);
    receiver.setControlPacketDispatcher(transactionManager);
    receiver.setSendPacketDispatcher(sender);

    // Create a timer for handling pings
    timer = new Timer("Snetworkmanager", true);

    // Initialize packet pool
    PacketPool.getPool();

    // Setup request handlers
    transactionManager.setRequestHandler(Packet.SESSION, new SessionRequestPacketHandler());
    transactionManager.setRequestHandler(Packet.UPDATE, new UpdateRequestPacketHandler());
    transactionManager.setRequestHandler(Packet.INFO, new InfoRequestPacketHandler());
    transactionManager.setRequestHandler(Packet.ISA, new IsaRequestPacketHandler());
    transactionManager.setRequestHandler(Packet.CONNECT, new ConnectRequestPacketHandler());
    transactionManager.setRequestHandler(Packet.INITIATE, new InitiateRequestPacketHandler());
}

From source file:org.apache.slide.webdav.event.NotificationTrigger.java

private NotificationTrigger() {
    Domain.log("Creating notification trigger", LOG_CHANNEL, Logger.INFO);
    try {/*  w  w w  .  j a  v a 2  s .  c  o m*/
        socket = new DatagramSocket();
    } catch (SocketException exception) {
        Domain.log("Server socket creation failed, no UDP notifications available", LOG_CHANNEL, Logger.ERROR);
        socket = null;
    }
}

From source file:org.motechproject.metrics.impl.StatsdAgentBackendImpl.java

private boolean send(ArrayList<String> stats) {
    DatagramSocket sock;/*from  ww  w.  jav  a 2 s.c  o m*/

    try {
        sock = new DatagramSocket();
    } catch (SocketException e) {
        //log.error(e.getMessage());
        return false;
    }

    boolean retval = false; // didn't send anything
    for (String stat : stats) {
        if (doSend(sock, stat)) {
            retval = true;
        }
    }

    return retval;
}