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, InetAddress laddr) throws SocketException 

Source Link

Document

Creates a datagram socket, bound to the specified local address.

Usage

From source file:org.lwes.listener.DatagramEnqueuer.java

@Override
public void initialize() throws IOException {
    if (address == null) {
        address = InetAddress.getByName(DEFAULT_ADDRESS);
    }/*w  ww .java 2  s.c om*/

    if (address.isMulticastAddress()) {
        socket = new MulticastSocket(port);
        ((MulticastSocket) socket).setTimeToLive(ttl);
        if (iface != null) {
            ((MulticastSocket) socket).setInterface(iface);
        }
        ((MulticastSocket) socket).joinGroup(address);
    } else {
        if (iface != null) {
            socket = new DatagramSocket(port, iface);
        } else {
            socket = new DatagramSocket(port, address);
        }

        if (port == 0) {
            port = socket.getLocalPort();
        }
    }
    int bufSize = MAX_DATAGRAM_SIZE * 50;
    String bufSizeStr = System.getProperty("MulticastReceiveBufferSize");
    if (bufSizeStr != null && !"".equals(bufSizeStr)) {
        bufSize = Integer.parseInt(bufSizeStr);
    }
    socket.setReceiveBufferSize(bufSize);
}

From source file:UDPInputStream.java

/************ opening and closing the stream ************/
/*/*w w  w.  j a v a2  s.c  o m*/
  *****************************************************************
  ***                        ***
  ***   Name :   open                                              ***
  ***   By   :   U. Bergstrom   (Creare Inc., Hanover, NH)   ***
  ***   For  :   E-Scan                  ***
  ***   Date :   October, 2001               ***
  ***                        ***
  ***   Copyright 2001 Creare Inc.            ***
  ***   All Rights Reserved               ***
  ***                        ***
  ***   Description :                  ***
  ***       The user may use this method to set the address and ***
  ***   port of the UDP socket to read from.                    ***
  ***                        ***
  *****************************************************************
*/
public void open(String address, int port) throws UnknownHostException, SocketException {

    dsock = new DatagramSocket(port, InetAddress.getByName(address));
}

From source file:org.opennms.netmgt.provision.server.SimpleUDPServer.java

/**
 * <p>getRunnable</p>/*from  ww w  .j  a  v  a 2 s. c  om*/
 *
 * @return a {@link java.lang.Runnable} object.
 * @throws java.lang.Exception if any.
 */
public SimpleServerRunnable getRunnable() throws IOException {
    return new SimpleServerRunnable() {

        @Override
        public void run() {
            try {
                m_socket = new DatagramSocket(getPort(), getInetAddress());
                m_socket.setSoTimeout(getTimeout());
                ready();

                attemptConversation(m_socket);
            } catch (Throwable e) {
                throw new UndeclaredThrowableException(e);
            } finally {
                IOUtils.closeQuietly(m_socket);
                finished();
                try {
                    // just in case we're stopping because of an exception
                    stopServer();
                } catch (final Exception e) {
                    LOG.info("error while stopping server", e);
                }
            }
        }

    };
}

From source file:org.mule.test.firewall.FirewallTestCase.java

protected DatagramSocket openUdpServer(InetAddress address, int port) throws IOException {
    try {//from www.  j  ava  2s .c  o  m
        return new DatagramSocket(port, address);
    } catch (IOException e) {
        logger.error("Could not open UDP server on " + addressToString(address, port));
        throw e;
    }
}

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

@SuppressWarnings("unchecked")
@Test// w w  w .ja va2 s .c  o  m
@Ignore
public void testMulticastReceiver() throws Exception {
    QueueChannel channel = new QueueChannel(2);
    int port = SocketUtils.findAvailableUdpSocket();
    MulticastReceivingChannelAdapter adapter = new MulticastReceivingChannelAdapter("225.6.7.8", port);
    adapter.setOutputChannel(channel);
    String nic = SocketTestUtils.chooseANic(true);
    if (nic == null) { // no multicast support
        LogFactory.getLog(this.getClass()).error("No Multicast support");
        return;
    }
    adapter.setLocalAddress(nic);
    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("225.6.7.8", port));
    new DatagramSocket(0, Inet4Address.getByName(nic)).send(packet);

    Message<byte[]> receivedMessage = (Message<byte[]>) channel.receive(2000);
    assertNotNull(receivedMessage);
    assertEquals(new String(message.getPayload()), new String(receivedMessage.getPayload()));
}

From source file:it.anyplace.sync.discovery.protocol.ld.LocalDiscorveryHandler.java

public void startListener() {
    listeningExecutorService.submit(new Runnable() {

        private final int incomingBufferSize = 1024; //TODO check this

        @Override/*from  w  w w .  j  a  v  a2  s .  c o m*/
        public void run() {
            try {
                if (datagramSocket == null || datagramSocket.isClosed()) {
                    datagramSocket = new DatagramSocket(UDP_PORT, InetAddress.getByName("0.0.0.0"));
                    logger.info("opening upd socket {}", datagramSocket.getLocalSocketAddress());
                }
                final DatagramPacket datagramPacket = new DatagramPacket(new byte[incomingBufferSize],
                        incomingBufferSize);
                logger.trace("waiting for message on socket addr = {}", datagramSocket.getLocalSocketAddress());
                isListening = true;
                datagramSocket.receive(datagramPacket);
                processingExecutorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            final String sourceAddress = datagramPacket.getAddress().getHostAddress();
                            ByteBuffer byteBuffer = ByteBuffer.wrap(datagramPacket.getData(),
                                    datagramPacket.getOffset(), datagramPacket.getLength());
                            int magic = byteBuffer.getInt(); //4 bytes
                            checkArgument(magic == MAGIC, "magic mismatch, expected %s, got %s", MAGIC, magic);
                            final LocalDiscoveryProtos.Announce announce = LocalDiscoveryProtos.Announce
                                    .parseFrom(ByteString.copyFrom(byteBuffer));
                            final String deviceId = hashDataToDeviceIdString(announce.getId().toByteArray());
                            if (!equal(deviceId, configuration.getDeviceId())) {
                                //                                logger.debug("received local announce from device id = {}", deviceId);
                                final List<DeviceAddress> deviceAddresses = Lists
                                        .newArrayList(Iterables.transform(
                                                firstNonNull(announce.getAddressesList(),
                                                        Collections.<String>emptyList()),
                                                new Function<String, DeviceAddress>() {
                                                    @Override
                                                    public DeviceAddress apply(String address) {
                                                        //                                /*
                                                        //                                When interpreting addresses with an unspecified address, e.g., tcp://0.0.0.0:22000 or tcp://:42424, the source address of the discovery announcement is to be used.
                                                        //                                 */
                                                        return DeviceAddress.newBuilder()
                                                                .setAddress(address.replaceFirst(
                                                                        "tcp://(0.0.0.0|):",
                                                                        "tcp://" + sourceAddress + ":"))
                                                                .setDeviceId(deviceId)
                                                                .setInstanceId(announce.getInstanceId())
                                                                .setProducer(
                                                                        DeviceAddress.AddressProducer.LOCAL_DISCOVERY)
                                                                .build();
                                                    }
                                                }));
                                boolean isNew = false;
                                synchronized (localDiscoveryRecords) {
                                    isNew = !localDiscoveryRecords.removeAll(deviceId).isEmpty();
                                    localDiscoveryRecords.putAll(deviceId, deviceAddresses);
                                }
                                eventBus.post(new MessageReceivedEvent() {
                                    @Override
                                    public List<DeviceAddress> getDeviceAddresses() {
                                        return Collections.unmodifiableList(deviceAddresses);
                                    }

                                    @Override
                                    public String getDeviceId() {
                                        return deviceId;
                                    }
                                });
                                if (isNew) {
                                    eventBus.post(new NewLocalPeerEvent() {
                                        @Override
                                        public String getDeviceId() {
                                            return deviceId;
                                        }
                                    });
                                }
                            }
                        } catch (Exception ex) {
                            logger.warn("error processing datagram", ex);
                        }
                    }
                });
                listeningExecutorService.submit(this);
            } catch (Exception ex) {
                isListening = false;
                if (listeningExecutorService.isShutdown()) {
                    return;
                }
                if (datagramSocket != null) {
                    logger.warn("error receiving datagram", ex);
                    listeningExecutorService.submit(this);
                } else if (ex instanceof java.net.BindException) {
                    logger.warn("error opening udp server socket : {}", ex.toString());
                } else {
                    logger.warn("error opening udp server socket", ex);
                }
            }
        }
    });
}

From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java

/**
 * Auxiliary method to start the discovery service.
 * /*from  w  ww .  jav a 2  s  . c o  m*/
 * @throws DiscoveryException
 *         thrown if the discovery service could not be started because
 *         of network difficulties
 */
private void startService() throws DiscoveryException {

    try {
        this.serverSocket = new DatagramSocket(this.discoveryPort, this.ipcAddress);
    } catch (SocketException e) {
        throw new DiscoveryException(e.toString());
    }

    LOG.info("Discovery service socket is bound to " + this.serverSocket.getLocalSocketAddress());

    this.isRunning = true;

    this.listeningThread = new Thread(this, "Discovery Service Thread");
    this.listeningThread.start();
}

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

/**
 * If receiving new datagrams fails with a {@link SocketException}, this
 * method is called to renew the socket - if possible.
 * //from w w  w  .  jav  a2 s .  com
 * @param socketException
 *            the exception that occurred.
 * @param failedSocket
 *            the socket that caused the exception. By default, he socket
 *            will be closed in order to be able to reopen it.
 *            Implementations may also try to reuse the socket, in
 *            dependence of the <code>socketException</code>.
 * @return the new socket or <code>null</code> if the listen thread should
 *         be terminated with the provided exception.
 * @throws SocketException
 *             a new socket exception if the socket could not be renewed.
 * @since 2.2.2
 */
protected DatagramSocket renewSocketAfterException(SocketException socketException, DatagramSocket failedSocket)
        throws SocketException {
    if ((failedSocket != null) && (!failedSocket.isClosed())) {
        failedSocket.close();
    }
    DatagramSocket s = new DatagramSocket(udpAddress.getPort(), udpAddress.getInetAddress());
    s.setSoTimeout(socketTimeout);
    return s;
}

From source file:cai.flow.collector.Collector.java

/**
 *
 * @throws Throwable/*w  w w.j av a2s  . c o  m*/
 */
public void reader_loop() throws Throwable {
    DatagramSocket socket;

    try {
        try {
            socket = new DatagramSocket(localPort, localHost);
            socket.setReceiveBufferSize(receiveBufferSize);
        } catch (IOException exc) {
            logger.fatal("Reader - socket create error: " + localHost + ":" + localPort);
            logger.debug(exc);
            throw exc;
        }

        while (true) {
            byte[] buf = new byte[2048];// 
            DatagramPacket p = null;
            if (p == null) {
                p = new DatagramPacket(buf, buf.length);

                try {
                    socket.receive(p);
                } catch (IOException exc) {
                    logger.error("Reader - socket read error: " + exc.getMessage());
                    logger.debug(exc);
                    put_to_queue(null);// notifyAll
                    break;
                }
            }

            if (this.sampler.shouldDue()) {
                put_to_queue(p);
            }
            p = null;
        }
    } catch (Throwable e) {
        logger.error("Exception trying to abort collector");
        put_to_queue(null);
        throw e;
    }
}

From source file:org.echocat.jomon.net.dns.DnsServer.java

public void serveUDP(InetSocketAddress address) {
    try {//from w ww .j  a  v a2  s . co m
        final DatagramSocket sock = new DatagramSocket(address.getPort(), address.getAddress());
        synchronized (_closeables) {
            _closeables.add(sock);
        }
        final short udpLength = 512;
        final byte[] in = new byte[udpLength];
        final DatagramPacket indp = new DatagramPacket(in, in.length);
        DatagramPacket outdp = null;
        while (!currentThread().isInterrupted()) {
            indp.setLength(in.length);
            receive(sock, indp);
            final Message query;
            byte[] response;
            try {
                query = new Message(in);
                response = generateReply(query, in, indp.getLength(), null);
                if (response == null) {
                    continue;
                }
            } catch (final IOException ignored) {
                response = formerrMessage(in);
            }
            if (outdp == null) {
                outdp = new DatagramPacket(response, response.length, indp.getAddress(), indp.getPort());
            } else {
                outdp.setData(response);
                outdp.setLength(response.length);
                outdp.setAddress(indp.getAddress());
                outdp.setPort(indp.getPort());
            }
            sock.send(outdp);
        }
    } catch (final InterruptedIOException ignored) {
        currentThread().interrupt();
    } catch (final IOException e) {
        LOG.warn("serveUDP(" + addrport(address.getAddress(), address.getPort()) + ")", e);
    }
}