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(int port) throws SocketException 

Source Link

Document

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

Usage

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

@Test
public void testWithSendingHostAndPortSameAsSender() throws IOException, InterruptedException {
    final String sendingHost = "localhost";
    final Integer sendingPort = 21001;
    runner.setProperty(ListenUDP.SENDING_HOST, sendingHost);
    runner.setProperty(ListenUDP.SENDING_HOST_PORT, String.valueOf(sendingPort));

    // bind to the same sending port that processor has for Sending Host Port
    final DatagramSocket socket = new DatagramSocket(sendingPort);

    final List<String> messages = getMessages(6);
    final int expectedQueued = messages.size();
    final int expectedTransferred = messages.size();

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

    List<MockFlowFile> mockFlowFiles = runner.getFlowFilesForRelationship(ListenUDP.REL_SUCCESS);
    verifyFlowFiles(mockFlowFiles);//from w  w w  .  ja va2 s.  c  o  m
    verifyProvenance(expectedTransferred);
}

From source file:net.spfbl.dnsbl.QueryDNSBL.java

/**
 * Configurao e intanciamento do servidor.
 * @throws java.net.SocketException se houver falha durante o bind.
 */// www. j av  a2s  . co  m
public QueryDNSBL(int port) throws SocketException {
    super("SERVERDNS");
    setPriority(Thread.NORM_PRIORITY);
    // Criando conexes.
    Server.logDebug("binding DNSBL socket on port " + port + "...");
    PORT = port;
    SERVER_SOCKET = new DatagramSocket(port);
}

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

@Test
public void testWithSendingHostAndPortDifferentThanSender() throws IOException, InterruptedException {
    final String sendingHost = "localhost";
    final Integer sendingPort = 21001;
    runner.setProperty(ListenUDP.SENDING_HOST, sendingHost);
    runner.setProperty(ListenUDP.SENDING_HOST_PORT, String.valueOf(sendingPort));

    // bind to a different sending port than the processor has for Sending Host Port
    final DatagramSocket socket = new DatagramSocket(21002);

    // no messages should come through since we are listening for 21001 and sending from 21002

    final List<String> messages = getMessages(6);
    final int expectedQueued = 0;
    final int expectedTransferred = 0;

    run(socket, messages, expectedQueued, expectedTransferred);
    runner.assertAllFlowFilesTransferred(ListenUDP.REL_SUCCESS, 0);
}

From source file:org.psit.transwatcher.TransWatcher.java

private String connectAndGetCardIP() {
    DatagramSocket clientSocket = null, serverSocket = null;

    try {// w ww.j  a v  a 2  s .co m
        String broadcastIP = getBroadcastIP();
        setState(broadcastIP == null ? State.NO_WIFI : State.SEARCHING_CARD);
        notifyMessage("BroadcastIP: " + broadcastIP);

        // send out broadcast
        clientSocket = new DatagramSocket(58255);
        InetAddress IPAddress = InetAddress.getByName(broadcastIP);
        byte[] sendData = "".getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 55777);
        clientSocket.send(sendPacket);
        clientSocket.close();

        serverSocket = new DatagramSocket(58255);
        byte[] receiveData = new byte[256];
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        serverSocket.setSoTimeout(3000);
        serverSocket.receive(receivePacket);
        serverSocket.close();

        notifyMessage("Packet received: " + new String(receiveData));
        if (new String(receivePacket.getData()).indexOf("Transcend WiFiSD") >= 0)
            return receivePacket.getAddress().getHostAddress();
    } catch (Exception ex) {
        notifyMessage("Card handshake unsuccessful. ");
        notifyException(ex);
    } finally {
        if (clientSocket != null)
            clientSocket.close();
        if (serverSocket != null)
            serverSocket.close();
    }
    return null;
}

From source file:net.mybox.mybox.Common.java

/**
 * Checks to see if a specific port is available.
 *
 * @param port the port to check for availability
 *///www  .j av  a 2s . c  o  m
public static boolean portAvailable(int port) {
    if (port < 0 || port > 65535) {
        throw new IllegalArgumentException("Invalid start port: " + port);
    }

    ServerSocket ss = null;
    DatagramSocket ds = null;
    try {
        ss = new ServerSocket(port);
        ss.setReuseAddress(true);
        ds = new DatagramSocket(port);
        ds.setReuseAddress(true);
        return true;
    } catch (IOException e) {
    } finally {
        if (ds != null) {
            ds.close();
        }

        if (ss != null) {
            try {
                ss.close();
            } catch (IOException e) {
                /* should not be thrown */
            }
        }
    }

    return false;
}

From source file:com.clustercontrol.agent.Agent.java

/**
 * ??awakeAgent?//from   www.  j a  v  a2 s  . co m
 * Agent.properties???UDP?24005??????????(releaseLatch)
 * ????ReceiveTopic????Topic????
 */
public void waitAwakeAgent() {
    final int BUFSIZE = 1;

    byte[] buf = new byte[BUFSIZE];
    InetAddress cAddr; // ??IP
    int cPort; // ???
    DatagramSocket sock = null;
    boolean flag = true;
    int port = 24005;

    int awakeDelay = 1000;

    try {
        String awakeDelayStr = AgentProperties.getProperty("awake.delay", Integer.toString(1000));
        awakeDelay = Integer.parseInt(awakeDelayStr);
        m_log.info("awake.delay = " + awakeDelay + " msec");
    } catch (NumberFormatException e) {
        m_log.error("awake.delay", e);
    }

    while (true) {
        /*
         * UDP???flag?true??
         * ?????flag?false?????getTopic(releaseLatch)?
         * 
         * UDP???????getTopic????????
         * ??????
         */
        try {
            if (sock != null && port != awakePort) {
                sock.close();
                sock = null;
            }
            if (sock == null || !sock.isBound()) {
                port = awakePort;
                sock = new DatagramSocket(port);
                sock.setSoTimeout(awakeDelay);
            }
            DatagramPacket recvPacket = new DatagramPacket(buf, BUFSIZE);
            sock.receive(recvPacket);
            cAddr = recvPacket.getAddress();
            cPort = recvPacket.getPort();
            flag = true;
            m_log.info("waitAwakeAgent (" + cAddr.getHostAddress() + " onPort=" + cPort + ") buf.length="
                    + buf.length);
        } catch (SocketTimeoutException e) {
            if (flag) {
                m_log.info("waitAwakeAgent packet end");
                m_receiveTopic.releaseLatch();
                flag = false;
            }
        } catch (Exception e) {
            String msg = "waitAwakeAgent port=" + awakePort + ", " + e.getClass().getSimpleName() + ", "
                    + e.getMessage();
            if (e instanceof BindException) {
                m_log.warn(msg);
            } else {
                m_log.warn(msg, e);
            }
            try {
                Thread.sleep(60 * 1000);
            } catch (InterruptedException e1) {
                m_log.warn(e1, e1);
            }
        }
    }
}

From source file:org.springframework.integration.ip.udp.UdpChannelAdapterTests.java

@Test
public void testUnicastReceiverException() throws Exception {
    SubscribableChannel channel = new DirectChannel();
    int port = SocketUtils.findAvailableUdpSocket();
    UnicastReceivingChannelAdapter adapter = new UnicastReceivingChannelAdapter(port);
    adapter.setOutputChannel(channel);/* www.j  a  v a 2s . co m*/
    //      SocketUtils.setLocalNicIfPossible(adapter);
    adapter.setOutputChannel(channel);
    ServiceActivatingHandler handler = new ServiceActivatingHandler(new FailingService());
    channel.subscribe(handler);
    QueueChannel errorChannel = new QueueChannel();
    adapter.setErrorChannel(errorChannel);
    adapter.start();
    SocketTestUtils.waitListening(adapter);

    Message<byte[]> message = MessageBuilder.withPayload("ABCD".getBytes()).build();
    DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper();
    DatagramPacket packet = mapper.fromMessage(message);
    packet.setSocketAddress(new InetSocketAddress("localhost", port));
    new DatagramSocket(SocketUtils.findAvailableUdpSocket()).send(packet);
    Message<?> receivedMessage = errorChannel.receive(2000);
    assertNotNull(receivedMessage);
    assertEquals("Failed", ((Exception) receivedMessage.getPayload()).getCause().getMessage());
}

From source file:edu.hawaii.soest.kilonalu.adam.AdamDispatcher.java

/**
 * A method used to connect to the UDP port of the host that will have the 
 * UDP stream of data packets, and that will also connect each of the AdamSource
 * drivers to the DataTurbine./*w  ww . j a v a  2 s . c  o m*/
 */
protected boolean connect() {
    if (isConnected()) {
        return true;
    }

    try {
        // bind to the UDP socket
        this.datagramSocket = new DatagramSocket(getHostPort());

        // Create a list of sensors from the properties file, and iterate through
        // the list, creating an RBNB Source object for each sensor listed. Store
        // these objects in a HashMap for later referral.

        this.sourceMap = new HashMap<String, AdamSource>();

        List sensorList = this.xmlConfiguration.getList("sensor.address");

        // declare the properties that will be pulled from the 
        // sensor.properties.xml file
        String address = "";
        String sourceName = "";
        String cacheSize = "";
        String archiveSize = "";
        String archiveChannel = "";

        // evaluate each sensor listed in the sensor.properties.xml file
        for (Iterator sIterator = sensorList.iterator(); sIterator.hasNext();) {

            // get each property value of the sensor
            int index = sensorList.indexOf(sIterator.next());
            address = (String) this.xmlConfiguration.getProperty("sensor(" + index + ").address");
            sourceName = (String) this.xmlConfiguration.getProperty("sensor(" + index + ").name");
            cacheSize = (String) this.xmlConfiguration.getProperty("sensor(" + index + ").cacheSize");
            archiveSize = (String) this.xmlConfiguration.getProperty("sensor(" + index + ").archiveSize");

            // given the properties, create an RBNB Source object
            AdamSource adamSource = new AdamSource(this.serverName, (new Integer(this.serverPort)).toString(),
                    this.archiveMode, (new Integer(archiveSize).intValue()),
                    (new Integer(cacheSize).intValue()), sourceName);
            adamSource.startConnection();
            sourceMap.put(address, adamSource);

        }
        connected = true;

    } catch (SocketException se) {
        System.err.println(
                "Failed to connect to the UDP data stream. " + "The error message was: " + se.getMessage());

    }

    return connected;
}

From source file:org.messic.service.MessicMain.java

/**
 * From apache camel Checks to see if a specific port is available.
 * //from  w w w  .  java  2s.c om
 * @param port the port to check for availability
 */
public static boolean isPortAvailable(int port) {
    ServerSocket ss = null;
    DatagramSocket ds = null;
    try {
        ss = new ServerSocket(port);
        ss.setReuseAddress(true);
        ds = new DatagramSocket(port);
        ds.setReuseAddress(true);
        return true;
    } catch (IOException e) {
    }

    finally {
        if (ds != null) {
            ds.close();
        }

        if (ss != null) {
            try {
                ss.close();
            } catch (IOException e) {
                /* should not be thrown */
            }
        }
    }

    return false;
}

From source file:org.springframework.integration.ip.util.SocketUtils.java

public static int findAvailableUdpSocket(int seed) {
    for (int i = seed; i < seed + 200; i++) {
        try {/*from  w  ww  .j ava  2s . c  o m*/
            DatagramSocket sock = new DatagramSocket(i);
            sock.close();
            Thread.sleep(100);
            return i;
        } catch (Exception e) {
        }
    }
    throw new RuntimeException("Cannot find a free server socket");
}