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:PeerDiscovery.java

/**
 * Constructs a UDP broadcast-based peer
 * //from w  ww.  j  a v  a 2s . co m
 * @param group
 *           The identifier shared by the peers that will be
 *           discovered.
 * @param port
 *           a valid port, i.e.: in the range 1025 to 65535
 *           inclusive
 * @throws IOException
 */
public PeerDiscovery(int group, int port) throws IOException {
    this.group = group;
    this.port = port;

    bcastSocket = new DatagramSocket(port);
    broadcastAddress = new InetSocketAddress("255.255.255.255", port);

    bcastListen.setDaemon(true);
    bcastListen.start();
}

From source file:nl.mindef.c2sc.nbs.olsr.pud.uplink.server.distributor.impl.DistributorWorkerImpl.java

public void init() throws IOException {
    this.sock = new DatagramSocket(null);
    this.sock.setReuseAddress(true);
    this.sock.bind(new InetSocketAddress(this.uplinkUdpPort));
}

From source file:net.fenyo.gnetwatch.actions.ActionFlood.java

/**
 * Floods the target.//from   ww w  .  j  av  a 2s  . c om
 * @param none.
 * @return void.
 * @throws IOException IO exception.
 * @throws InterruptedException exception.
 */
public void invoke() throws IOException, InterruptedException {
    if (isDisposed() == true)
        return;

    try {
        super.invoke();

        // il faudrait copier les queriers  la cration de l'action
        final IPQuerier querier;

        DatagramSocket socket;
        final byte[] buf;
        final DatagramPacket packet;
        // on invoque un champ persistent depuis potentiellement un thread autre que celui qu gre une session qui rend cet objet persistent, on doit viter cet accs concurrent (les sessions ne sont pas thread safe)
        synchronized (getGUI().getSynchro()) {
            if (TargetIPv4.class.isInstance(getTarget())) {
                querier = ((TargetIPv4) getTarget()).getIPQuerier();
            } else if (TargetIPv6.class.isInstance(getTarget())) {
                querier = ((TargetIPv6) getTarget()).getIPQuerier();
            } else
                return;

            socket = new DatagramSocket(querier.getPortSrc());
            socket.setTrafficClass(querier.getTos() << 2);
            socket.setBroadcast(true);

            buf = new byte[querier.getPDUMaxSize()];
            Arrays.fill(buf, (byte) 0);
            packet = new DatagramPacket(buf, buf.length,
                    new InetSocketAddress(querier.getAddress(), querier.getPortDst()));
        }

        long last_time = System.currentTimeMillis();
        int bytes_sent = 0;
        while (true) {
            socket.send(packet);
            bytes_sent += buf.length;

            if (System.currentTimeMillis() - last_time > 1000) {

                synchronized (getGUI().getSynchro()) {
                    synchronized (getGUI().sync_tree) {
                        final Session session = getGUI().getSynchro().getSessionFactory().getCurrentSession();
                        session.beginTransaction();
                        try {
                            session.update(this);

                            getTarget().addEvent(new EventFlood(new Double(
                                    ((double) 8 * 1000 * bytes_sent) / (System.currentTimeMillis() - last_time))
                                            .intValue()));

                            setDescription(
                                    GenericTools.formatNumericString(getGUI().getConfig(),
                                            "" + new Double(((double) 8 * 1000 * bytes_sent)
                                                    / (System.currentTimeMillis() - last_time)).intValue())
                                            + " bit/s");

                            session.getTransaction().commit();
                        } catch (final Exception ex) {
                            log.error("Exception", ex);
                            session.getTransaction().rollback();
                        }
                    }
                }

                synchronized (getGUI().getSynchro()) {
                    getGUI().setStatus(getGUI().getConfig().getPattern("bytes_flooded", bytes_sent,
                            querier.getAddress().toString().substring(1)));
                }

                last_time = System.currentTimeMillis();
                bytes_sent = 0;
            }

            if (interrupted == true) {
                socket.close();
                return;
            }
        }
    } catch (final InterruptedException ex) {
    }
}

From source file:ru.novoscan.trkpd.snmp.spring.TrackSpringSnmpAgent.java

public void run() {
    try {// w  w w .ja  v  a2 s.c o  m
        logger.debug("Binding to UDP port " + listeningPort);
        socket = new DatagramSocket(listeningPort);
    } catch (SocketException e) {
        // Fix: Flag to control lock socket within application
        isSocketException = true;
        throw new SnmpSystemException("Can not create SNMP agent UDP socket. Reason: " + e.getMessage());
    }

    // Fix: Flag to control lock socket within application
    isSocketCreated = true;

    while (!workerThread.isInterrupted()) {
        byte requestPacketBuffer[] = new byte[PACKET_MAX_SIZE];
        final DatagramPacket requestPacket = new DatagramPacket(requestPacketBuffer,
                requestPacketBuffer.length);
        try {
            socket.receive(requestPacket);
        } catch (IOException e) {
            logger.error("Error processing SNMP request. Reason: " + e.getMessage());
            continue;
        }
        final byte data[] = requestPacket.getData();
        Thread procThread = new Thread(new Runnable() {

            public void run() {
                try {
                    Message requestMsg;
                    Message responseMsg;
                    PDU requestPDU;
                    // Fix: Added missed ')' character
                    logger.debug("Received packet (length=" + data.length + " bytes)");
                    BerTlv tlv = new BerTlv();
                    tlv.decode(new ByteArrayInputStream(data));
                    requestMsg = new Message(tlv);
                    responseMsg = null;
                    requestPDU = (PDU) requestMsg.getPDU();
                    String requestedOID = requestPDU.getVarBindList().getVarBind(0).getObjectName()
                            .stringValue();

                    if (!hasHandledPrefix(requestedOID)) {

                        logger.info("No entry found for oid " + requestedOID);
                        GetResponsePDU responsePDU = new GetResponsePDU(requestPDU.getRequestId(), 2, 0L,
                                requestPDU.getVarBindList());
                        responseMsg = new Message(0, requestMsg.getComunity(), responsePDU);

                        return;
                    }

                    if (!validateCommunity(requestMsg)) {
                        logger.warn(
                                "Community [" + requestMsg.getComunity() + "] doesn't match for snmp request");
                        return;
                    }

                    GetResponsePDU responsePDU = null;
                    if (requestPDU instanceof GetRequestPDU)
                        responsePDU = handleGetRequest((GetRequestPDU) requestPDU);
                    else if (requestPDU instanceof GetNextRequestPDU)
                        responsePDU = handleGetNextRequest((GetNextRequestPDU) requestPDU);
                    else if (requestPDU instanceof SetRequestPDU)
                        responsePDU = handleSetRequest((SetRequestPDU) requestPDU);
                    else
                        responsePDU = createErrorResponse(requestPDU.getRequestId(), 5, 0,
                                requestPDU.getVarBindList());
                    responseMsg = new Message(0, requestMsg.getComunity(), responsePDU);

                    logger.info("Sending response to client\n" + responseMsg.toString());
                    byte responsePacketBuffer[] = responseMsg.toBerTlv().getBytes();
                    if (responsePacketBuffer.length > PACKET_MAX_SIZE) {
                        responsePDU = new GetResponsePDU(requestPDU.getRequestId(), 1, 0L,
                                requestPDU.getVarBindList());
                        responseMsg = new Message(SNMP_VERSION, requestMsg.getComunity(), responsePDU);
                        responsePacketBuffer = responseMsg.toBerTlv().getBytes();
                    }
                    DatagramPacket responsePacket = new DatagramPacket(responsePacketBuffer,
                            responsePacketBuffer.length, requestPacket.getAddress(), requestPacket.getPort());
                    socket.send(responsePacket);
                } catch (Exception e) {
                    logger.error("Error processing SNMP request. Reason: " + e.getMessage());
                }
            }
        });
        procThread.start();
    }
}

From source file:com.github.podd.resources.test.AbstractResourceImplTest.java

private static synchronized int getFreePort() {
    int result = -1;
    while (result <= 0) {
        // Avoid infinite loops when the majority of legitimate ports have been tried already
        // and the test suite is too big or broken somehow.
        Assert.assertTrue("No free ports left for parallel tests",
                AbstractResourceImplTest.usedPorts.size() < 50000);
        try (ServerSocket ss = new ServerSocket(0)) {
            ss.setReuseAddress(true);//from ww  w.jav  a 2  s . c o  m
            result = ss.getLocalPort();
            if (AbstractResourceImplTest.usedPorts.contains(result)) {
                result = -1;
            } else {
                // If the next port was already in used ports then the following will return
                // false and we will set result to -1
                if (AbstractResourceImplTest.usedPorts.add(result)) {
                    try (DatagramSocket ds = new DatagramSocket(result);) {
                        ds.setReuseAddress(true);
                    }
                } else {
                    result = -1;
                }
            }
        } catch (final IOException e) {
            result = -1;
        }
    }
    return result;
}

From source file:com.image32.demo.simpleapi.SimpleApiDemo.java

public static boolean checkPortAvailablity(int port) {

    ServerSocket ss = null;// w ww .j  av  a2  s .c om
    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) {
                return false;
            }
        }
    }
    return false;
}

From source file:jlg.jade.test.asterix.cat062.Cat062LargeSampleTest.java

@Test()
@Ignore("Can only be executed if an Asterix sender is feeding the decoder")
public void when_upd_unicast_is_used_as_input_should_decode_cat062_messages_from_larger_sample()
        throws IOException {
    //arrange//from  w  w w .j  av a  2  s  .co m
    final int PORT = 3002;
    final int MAX_PACKET_SIZE = 65507;
    final int TIMEOUT = 5000;

    //act
    AsterixDecoder decoder = new AsterixDecoder(62, 65);
    byte[] networkBuffer = new byte[MAX_PACKET_SIZE];
    int receivedDatagrams = 0;
    int receivedBytes = 0;
    try (DatagramSocket client = new DatagramSocket(PORT)) {
        client.setSoTimeout(TIMEOUT);
        DatagramPacket packet = new DatagramPacket(networkBuffer, networkBuffer.length);
        while (true) {
            client.receive(packet);
            decoder.decode(networkBuffer, 0, packet.getLength());

            //accumulate and print info
            receivedDatagrams++;
            receivedBytes += packet.getLength();
            if (receivedDatagrams % 100 == 0) {
                System.out
                        .println("Processed " + receivedDatagrams + " datagrams (" + receivedBytes + ") bytes");
            }
        }
    } catch (IOException e) {
        System.out.println("Processed " + receivedDatagrams + " datagrams (" + receivedBytes + ") bytes");
    }

    //assert
    int expectedDatagrams = 18163;
    int expectedBytes = 2785805;
    assertEquals(expectedDatagrams, receivedDatagrams);
    assertEquals(expectedBytes, receivedBytes);
}

From source file:net.sourceforge.vulcan.ant.receiver.UdpEventSource.java

protected DatagramSocket openSocket() {
    try {// ww  w .  ja  va2 s  .co  m
        final SocketAddress addr = new InetSocketAddress(listenAddress, port);
        final DatagramSocket socket = new DatagramSocket(addr);
        socket.setSoTimeout(timeout);
        this.port = socket.getLocalPort();
        return socket;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.clustercontrol.poller.impl.UdpTransportMappingImpl.java

private synchronized DatagramSocket ensureSocket() throws SocketException {
    DatagramSocket s = socket;/* w ww. j  av  a 2s .com*/
    if (s == null) {
        s = new DatagramSocket(udpAddress.getPort());
        s.setSoTimeout(socketTimeout);
        this.socket = s;
    }
    return s;
}

From source file:org.apache.webdav.lib.NotificationListener.java

/**
 * /* ww w . jav a  2  s.c  o  m*/
 * @param host The ip-address on which the udp or http-server is running (e.g. "localhost")
 * @param port The port where the udp or http-server is listening on (e.g. 4444)
 * @param repositoryHost The ip-adress of the WebDAV-repository
 * @param repositoryPort The port of the WebDAV-repository (e.g. 8080)
 * @param protocol The protocol that should be used to connect to the WebDAV-repository (http or https) 
 * @param credentials The credentials which are used to connect to the WebDAV-repository 
 * @param repositoryDomain The repository domain (e.g. "/slide")
 * @param pollInterval The poll interval that will be used if no notifications are revieved via UDP/TCP
 * @param udp If set to true, UDP server will be started, otherwise TCP server (must match the repository notification mode)
 */
public NotificationListener(String host, int port, String repositoryHost, int repositoryPort, Protocol protocol,
        Credentials credentials, String repositoryDomain, int pollInterval, boolean udp) {
    this.credentials = credentials;
    this.notificationHost = host;
    this.notificationPort = port;
    this.repositoryHost = repositoryHost;
    this.repositoryPort = repositoryPort;
    this.protocol = protocol;
    this.repositoryDomain = repositoryDomain;
    this.udp = udp;

    if (udp) {
        Thread listenerThread = new Thread(new Runnable() {
            public void run() {
                DatagramSocket serverSocket = null;
                try {
                    serverSocket = new DatagramSocket(notificationPort);
                    while (true) {
                        byte[] buf = new byte[256];
                        DatagramPacket packet = new DatagramPacket(buf, buf.length);
                        serverSocket.receive(packet);
                        BufferedReader reader = new BufferedReader(
                                new InputStreamReader(new ByteArrayInputStream(buf)));
                        parseNotification(reader);
                    }
                } catch (IOException e) {
                    logger.log(Level.SEVERE, "Error while listening to socket", e);
                }
            }
        });
        listenerThread.setDaemon(true);
        listenerThread.start();
    } else {
        Thread listenerThread = new Thread(new Runnable() {
            public void run() {
                ServerSocket serverSocket = null;
                try {
                    serverSocket = new ServerSocket(notificationPort);
                    while (true) {
                        new ConnectionThread(serverSocket.accept()).start();
                    }
                } catch (IOException e) {
                    logger.log(Level.SEVERE, "Error while listening to socket", e);
                }
            }
        });
        listenerThread.setDaemon(true);
        listenerThread.start();
    }

    TimerTask poll = new TimerTask() {
        public void run() {
            if (subscribersAsString != null) {
                poll(subscribersAsString);
            }
        }
    };
    timer.schedule(poll, pollInterval, pollInterval);
}