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.rifidi.emulator.io.comm.ip.udp.UDPCommunicationTest.java

/**
 * Tests turning on the UDPCommunication while it is off.
 * /*from  www  .j ava  2s. c o m*/
 *  
 */
public void testTurnOnWhenOff() {

    /* Data to send */
    byte[] dataToSend = message.getBytes();

    /* Error code -- gets modified if exceptions occur. */
    boolean error = false;

    /* Attempt to connect to the specified IP/Port using UDP */
    this.udpComm.turnOn();

    /* Allow server socket to fully start */
    synchronized (this) {
        try {
            this.wait(1000);
        } catch (InterruptedException e2) {
            /* Do nothing */
        }
        this.notifyAll();
    }

    /* Make a client */
    DatagramSocket clientSocket = null;
    try {
        clientSocket = new DatagramSocket(this.udpComm.getRemotePort());
    } catch (SocketException e) {
        logger.debug(this.getName() + ": " + e.getMessage());
        error = true;
    }

    /* Send out a packet of data */
    try {
        this.udpComm.getSendBuffer().addToBuffer(dataToSend);
    } catch (DataBufferInterruptedException dbie) {
        logger.debug(this.getName() + ": " + dbie.getMessage());
        error = true;
    }

    /* Receive the packet of data */
    if (clientSocket != null) {
        /* Set a timeout for receiving data */
        try {
            clientSocket.setSoTimeout(1000);
        } catch (SocketException e) {
            logger.debug(this.getName() + ": " + e.getMessage());
            error = true;
        }

        /* Make a new packet to hold the received data */
        DatagramPacket dataPacket = new DatagramPacket(new byte[1024], 1024);

        /* Attempt to receive the data */
        try {
            clientSocket.receive(dataPacket);
        } catch (IOException e) {
            logger.debug(this.getName() + ": " + e.getMessage());
            error = true;
        }

        /* Check that the data was received succesfully */
        if (!error) {
            logger.debug("Client received: " + new String(dataPacket.getData()));
        } else {
            logger.debug(this.getName() + ": client did not receive message.");
            error = true;
        }

        clientSocket.disconnect();

        clientSocket.close();
        clientSocket = null;

    }

    /* Check to see if any errors happened. */
    assertFalse(error);

}

From source file:org.zxg.network.dhtcrawler.Crawler.java

public void start() throws SocketException, NoSuchAlgorithmException {
    btCrawler = new BtCrawler(this.crawlerListener);
    btCrawler.start();/*  w  w w . j  av  a2  s . c om*/
    nodeId = Util.randomId();
    routeTable = new RouteTable(nodeId);
    dhtReqMethodCache = new ConcurrentHashMap<>();
    socket = new DatagramSocket(new InetSocketAddress(host, port));
    receiveThread = new ReceiveThread();
    receiveThread.start();
    timer = new Timer(true);
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            clearDhtReqMethodCache();
        }
    }, 900000, 900000);
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            try {
                maintainRouteTable();
            } catch (Exception ex) {
                Logger.getLogger(Crawler.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }, 1000, 1000);
}

From source file:com.springrts.springls.nat.NatHelpServer.java

@Override
public void run() {

    Configuration conf = getContext().getService(Configuration.class);
    int port = conf.getInt(ServerConfiguration.NAT_PORT);
    try {//from   ww w.j a v a 2s.  c o  m
        socket = new DatagramSocket(port);
    } catch (Exception ex) {
        LOG.warn("Unable to start UDP server on port " + port + ". Ignoring ...", ex);
        return;
    }

    LOG.info("Listening for connections on UDP port {} ...", port);

    byte[] buffer = new byte[RECEIVE_BUFFER_SIZE];
    while (true) {
        try {
            if (myThread.isInterrupted()) {
                break;
            }

            // receive packet
            DatagramPacket packet = new DatagramPacket(buffer, RECEIVE_BUFFER_SIZE);
            socket.receive(packet);
            msgList.add(packet);
        } catch (InterruptedIOException e) {
            break;
        } catch (IOException ex) {
            if (!ex.getMessage().equalsIgnoreCase("socket closed")) {
                LOG.error("Error in UDP server", ex);
            }
        }
    }

    socket.close();
    LOG.info("UDP NAT server closed.");
}

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

@SuppressWarnings("unchecked")
@Test//  w  w w.j a  va  2 s  .  c  o  m
public void testUnicastReceiverWithReply() throws Exception {
    QueueChannel channel = new QueueChannel(2);
    int port = SocketUtils.findAvailableUdpSocket();
    UnicastReceivingChannelAdapter adapter = new UnicastReceivingChannelAdapter(port);
    adapter.setOutputChannel(channel);
    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));
    final DatagramSocket socket = new DatagramSocket(SocketUtils.findAvailableUdpSocket());
    socket.send(packet);
    final AtomicReference<DatagramPacket> theAnswer = new AtomicReference<DatagramPacket>();
    final CountDownLatch receiverReadyLatch = new CountDownLatch(1);
    final CountDownLatch replyReceivedLatch = new CountDownLatch(1);
    //main thread sends the reply using the headers, this thread will receive it
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            DatagramPacket answer = new DatagramPacket(new byte[2000], 2000);
            try {
                receiverReadyLatch.countDown();
                socket.receive(answer);
                theAnswer.set(answer);
                replyReceivedLatch.countDown();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    Message<byte[]> receivedMessage = (Message<byte[]>) channel.receive(2000);
    assertEquals(new String(message.getPayload()), new String(receivedMessage.getPayload()));
    String replyString = "reply:" + System.currentTimeMillis();
    byte[] replyBytes = replyString.getBytes();
    DatagramPacket reply = new DatagramPacket(replyBytes, replyBytes.length);
    reply.setSocketAddress(
            new InetSocketAddress((String) receivedMessage.getHeaders().get(IpHeaders.IP_ADDRESS),
                    (Integer) receivedMessage.getHeaders().get(IpHeaders.PORT)));
    assertTrue(receiverReadyLatch.await(10, TimeUnit.SECONDS));
    new DatagramSocket().send(reply);
    assertTrue(replyReceivedLatch.await(10, TimeUnit.SECONDS));
    DatagramPacket answerPacket = theAnswer.get();
    assertNotNull(answerPacket);
    assertEquals(replyString, new String(answerPacket.getData(), 0, answerPacket.getLength()));
}

From source file:fr.fastconnect.factory.tibco.bw.maven.bwengine.AbstractServiceEngineMojo.java

public static boolean available(int port, int minPort, int maxPort) {
    if (port < minPort || port > maxPort || port > 65535) {
        throw new IllegalArgumentException("Invalid start port: " + port);
    }/*from  w  ww .j  a  v  a2s  . c  om*/

    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:nl.mindef.c2sc.nbs.olsr.pud.uplink.server.cluster.impl.RelayClusterReceiverImpl.java

public void init() throws SocketException {
    this.setName(this.getClass().getSimpleName());
    this.sock = new DatagramSocket(null);
    this.sock.setReuseAddress(true);
    this.sock.bind(new InetSocketAddress(this.relayClusterUdpPort));
    this.start();
}

From source file:org.openhab.binding.tacmi.internal.TACmiBinding.java

/**
 * Called by the SCR to activate the component with its configuration read
 * from CAS//from  w  w w.java 2s.  c  om
 * 
 * @param bundleContext
 *            BundleContext of the Bundle that defines this component
 * @param configuration
 *            Configuration properties for this component obtained from the
 *            ConfigAdmin service
 */
public void activate(final BundleContext bundleContext, final Map<String, Object> configuration) {
    this.bundleContext = bundleContext;

    // to override the default refresh interval one has to add a
    // parameter to openhab.cfg like <bindingName>:refresh=<intervalInMs>
    String refreshIntervalString = (String) configuration.get("refresh");
    if (StringUtils.isNotBlank(refreshIntervalString)) {
        refreshInterval = Long.parseLong(refreshIntervalString);
    }

    // set cmiAddress from configuration
    //cmiAddress = (String) configuration.get("cmiAddress");
    try {
        cmiAddress = InetAddress.getByName((String) configuration.get("cmiAddress"));
    } catch (UnknownHostException e1) {
        logger.error("Failed to get IP of CMI from configuration");
        setProperlyConfigured(false);
        return;
    }

    try {
        clientSocket = new DatagramSocket(cmiPort);
    } catch (SocketException e) {
        logger.error("Failed to create Socket for receiving UDP packts from CMI");
        setProperlyConfigured(true);
        return;
    }

    setProperlyConfigured(true);
}

From source file:eu.eubrazilcc.lvl.core.util.NetworkingUtils.java

public static final boolean isPortAvailable(final int port) throws IllegalArgumentException {
    checkArgument(USER_PORTS_16_BITS.contains(port), "Invalid start port: " + port);
    try (final ServerSocket ss = new ServerSocket(port); final DatagramSocket ds = new DatagramSocket(port)) {
        ss.setReuseAddress(true);/*from  w  w  w . j  a v  a 2 s.co m*/
        ds.setReuseAddress(true);
        return true;
    } catch (IOException ignore) {
    }
    return false;
}

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

@Test
public void verifySendWithAck() throws Exception {

    final List<Integer> openPorts = SocketUtils.findAvailableUdpSockets(SocketUtils.getRandomSeedPort(), 2);

    final int testPort = openPorts.get(0);
    final int ackPort = openPorts.get(1);

    byte[] buffer = new byte[1000];
    final DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length);
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    UnicastSendingMessageHandler handler = new UnicastSendingMessageHandler("localhost", testPort, true, true,
            "localhost", ackPort, 5000);
    handler.afterPropertiesSet();/*from  w  w w . ja v  a  2s.com*/
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            try {
                DatagramSocket socket = new DatagramSocket(testPort);
                latch1.countDown();
                socket.receive(receivedPacket);
                socket.close();
                DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper();
                mapper.setAcknowledge(true);
                mapper.setLengthCheck(true);
                Message<byte[]> message = mapper.toMessage(receivedPacket);
                Object id = message.getHeaders().get(IpHeaders.ACK_ID);
                byte[] ack = id.toString().getBytes();
                DatagramPacket ackPack = new DatagramPacket(ack, ack.length,
                        new InetSocketAddress("localHost", ackPort));
                DatagramSocket out = new DatagramSocket();
                out.send(ackPack);
                out.close();
                latch2.countDown();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    latch1.await(3000, TimeUnit.MILLISECONDS);
    String payload = "foobar";
    handler.handleMessage(MessageBuilder.withPayload(payload).build());
    assertTrue(latch2.await(10000, TimeUnit.MILLISECONDS));
    byte[] src = receivedPacket.getData();
    int length = receivedPacket.getLength();
    int offset = receivedPacket.getOffset();
    byte[] dest = new byte[6];
    System.arraycopy(src, offset + length - 6, dest, 0, 6);
    assertEquals(payload, new String(dest));
    handler.shutDown();
}

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

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