Search in sources :

Example 66 with DatagramSocket

use of java.net.DatagramSocket in project netty by netty.

the class EpollReuseAddrTest method testMultipleBindDatagramChannel.

@Test(timeout = 10000)
// TODO: Unignore after making it pass on centos6-1 and debian7-1
@Ignore
public void testMultipleBindDatagramChannel() throws Exception {
    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.ADVANCED);
    Assume.assumeTrue(versionEqOrGt(3, 9, 0));
    Bootstrap bootstrap = createBootstrap();
    bootstrap.option(EpollChannelOption.SO_REUSEPORT, true);
    final AtomicBoolean received1 = new AtomicBoolean();
    bootstrap.handler(new DatagramSocketTestHandler(received1));
    ChannelFuture future = bootstrap.bind().syncUninterruptibly();
    final InetSocketAddress address1 = (InetSocketAddress) future.channel().localAddress();
    final AtomicBoolean received2 = new AtomicBoolean();
    bootstrap.handler(new DatagramSocketTestHandler(received2));
    ChannelFuture future2 = bootstrap.bind().syncUninterruptibly();
    final InetSocketAddress address2 = (InetSocketAddress) future2.channel().localAddress();
    Assert.assertEquals(address1, address2);
    final byte[] bytes = "data".getBytes();
    // fire up 16 Threads and send DatagramPackets to make sure we stress it enough to see DatagramPackets received
    // on both sockets.
    int count = 16;
    final CountDownLatch latch = new CountDownLatch(count);
    Runnable r = new Runnable() {

        @Override
        public void run() {
            try {
                DatagramSocket socket = new DatagramSocket();
                while (!received1.get() || !received2.get()) {
                    socket.send(new DatagramPacket(bytes, 0, bytes.length, address1.getAddress(), address1.getPort()));
                }
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            latch.countDown();
        }
    };
    ExecutorService executor = Executors.newFixedThreadPool(count);
    for (int i = 0; i < count; i++) {
        executor.execute(r);
    }
    latch.await();
    executor.shutdown();
    future.channel().close().syncUninterruptibly();
    future2.channel().close().syncUninterruptibly();
    Assert.assertTrue(received1.get());
    Assert.assertTrue(received2.get());
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) DatagramSocket(java.net.DatagramSocket) DatagramPacket(java.net.DatagramPacket) ExecutorService(java.util.concurrent.ExecutorService) AbstractBootstrap(io.netty.bootstrap.AbstractBootstrap) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 67 with DatagramSocket

use of java.net.DatagramSocket in project openhab1-addons by openhab.

the class HarmonyHubDiscovery method sendDiscoveryMessage.

/**
     * Send broadcast message over all active interfaces
     *
     * @param discoverString
     *            String to be used for the discovery
     */
private void sendDiscoveryMessage(String discoverString) {
    DatagramSocket bcSend = null;
    try {
        bcSend = new DatagramSocket();
        bcSend.setBroadcast(true);
        byte[] sendData = discoverString.getBytes();
        // Broadcast the message over all the network interfaces
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                continue;
            }
            for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                InetAddress[] broadcast = new InetAddress[3];
                broadcast[0] = InetAddress.getByName("224.0.0.1");
                broadcast[1] = InetAddress.getByName("255.255.255.255");
                broadcast[2] = interfaceAddress.getBroadcast();
                broadcast[3] = InetAddress.getByName(optionalHost);
                for (InetAddress bc : broadcast) {
                    // Send the broadcast package!
                    if (bc != null && !bc.isLoopbackAddress()) {
                        try {
                            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, bc, DISCO_PORT);
                            bcSend.send(sendPacket);
                        } catch (IOException e) {
                            logger.error("IO error during HarmonyHub discovery: {}", e.getMessage());
                        } catch (Exception e) {
                            logger.error(e.getMessage(), e);
                        }
                        logger.trace("Request packet sent to: {} Interface: {}", bc.getHostAddress(), networkInterface.getDisplayName());
                    }
                }
            }
        }
    } catch (IOException e) {
        logger.debug("IO error during HarmonyHub discovery: {}", e.getMessage());
    } finally {
        try {
            if (bcSend != null) {
                bcSend.close();
            }
        } catch (Exception e) {
        // Ignore
        }
    }
}
Also used : DatagramSocket(java.net.DatagramSocket) InterfaceAddress(java.net.InterfaceAddress) DatagramPacket(java.net.DatagramPacket) NetworkInterface(java.net.NetworkInterface) IOException(java.io.IOException) InetAddress(java.net.InetAddress) IOException(java.io.IOException)

Example 68 with DatagramSocket

use of java.net.DatagramSocket in project openhab1-addons by openhab.

the class AnelUDPConnector method sendDatagram.

/**
     * Send data to the specified address via the specified UDP port.
     *
     * @param data
     *            The data to send.
     * @throws Exception
     *             If an exception occurred.
     */
void sendDatagram(byte[] data) throws Exception {
    if (data == null || data.length == 0) {
        throw new IllegalArgumentException("data must not be null or empty");
    }
    try {
        final InetAddress ipAddress = InetAddress.getByName(host);
        final DatagramPacket packet = new DatagramPacket(data, data.length, ipAddress, sendPort);
        final DatagramSocket socket = new DatagramSocket();
        socket.send(packet);
        socket.close();
    } catch (SocketException e) {
        throw new Exception(e);
    } catch (UnknownHostException e) {
        throw new Exception("Could not resolve host: " + host, e);
    } catch (IOException e) {
        throw new Exception(e);
    }
}
Also used : SocketException(java.net.SocketException) UnknownHostException(java.net.UnknownHostException) DatagramSocket(java.net.DatagramSocket) DatagramPacket(java.net.DatagramPacket) IOException(java.io.IOException) InetAddress(java.net.InetAddress) SocketException(java.net.SocketException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException)

Example 69 with DatagramSocket

use of java.net.DatagramSocket in project openhab1-addons by openhab.

the class AnelUDPConnector method receiveDatagram.

/**
     * This is a blocking call for receiving data from the specific UDP port.
     *
     * @return The received data.
     * @throws Exception
     *             If an exception occurred.
     */
byte[] receiveDatagram() throws Exception {
    try {
        if (socket == null) {
            socket = new DatagramSocket(receivePort);
        }
        // Create a packet
        final DatagramPacket packet = new DatagramPacket(new byte[MAX_PACKET_SIZE], MAX_PACKET_SIZE);
        // Receive a packet (blocking)
        socket.receive(packet);
        return Arrays.copyOfRange(packet.getData(), 0, packet.getLength() - 1);
    } catch (SocketException e) {
        if (e.getMessage() != null && e.getMessage().equals("socket closed")) {
            // happens during shutdown
            return null;
        }
        throw new Exception(e);
    } catch (IOException e) {
        throw new Exception(e);
    }
}
Also used : SocketException(java.net.SocketException) DatagramSocket(java.net.DatagramSocket) DatagramPacket(java.net.DatagramPacket) IOException(java.io.IOException) SocketException(java.net.SocketException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException)

Example 70 with DatagramSocket

use of java.net.DatagramSocket in project openhab1-addons by openhab.

the class NibeHeatPumpUDPConnector method receiveDatagram.

@Override
public byte[] receiveDatagram() throws NibeHeatPumpException {
    final int PACKETSIZE = 255;
    try {
        if (socket == null) {
            socket = new DatagramSocket(port);
        }
        // Create a packet
        DatagramPacket packet = new DatagramPacket(new byte[PACKETSIZE], PACKETSIZE);
        // Receive a packet (blocking)
        socket.receive(packet);
        return Arrays.copyOfRange(packet.getData(), 0, packet.getLength());
    } catch (SocketException e) {
        throw new NibeHeatPumpException(e);
    } catch (IOException e) {
        throw new NibeHeatPumpException(e);
    }
}
Also used : SocketException(java.net.SocketException) DatagramSocket(java.net.DatagramSocket) NibeHeatPumpException(org.openhab.binding.nibeheatpump.internal.NibeHeatPumpException) DatagramPacket(java.net.DatagramPacket) IOException(java.io.IOException)

Aggregations

DatagramSocket (java.net.DatagramSocket)294 DatagramPacket (java.net.DatagramPacket)137 IOException (java.io.IOException)112 SocketException (java.net.SocketException)74 InetAddress (java.net.InetAddress)63 InetSocketAddress (java.net.InetSocketAddress)46 UnknownHostException (java.net.UnknownHostException)33 Test (org.junit.Test)27 SocketTimeoutException (java.net.SocketTimeoutException)24 InterruptedIOException (java.io.InterruptedIOException)18 PortUnreachableException (java.net.PortUnreachableException)18 ServerSocket (java.net.ServerSocket)18 BindException (java.net.BindException)16 IllegalBlockingModeException (java.nio.channels.IllegalBlockingModeException)16 DatagramChannel (java.nio.channels.DatagramChannel)14 MockEndpoint (org.apache.camel.component.mock.MockEndpoint)11 MulticastSocket (java.net.MulticastSocket)10 SocketAddress (java.net.SocketAddress)9 ByteBuffer (java.nio.ByteBuffer)8 ArrayList (java.util.ArrayList)6