Example usage for java.net DatagramSocket close

List of usage examples for java.net DatagramSocket close

Introduction

In this page you can find the example usage for java.net DatagramSocket close.

Prototype

public void close() 

Source Link

Document

Closes this datagram socket.

Usage

From source file:org.wso2.carbon.device.mgt.iot.agent.firealarm.transport.TransportUtils.java

private static boolean checkIfPortAvailable(int port) {
    ServerSocket tcpSocket = null;
    DatagramSocket udpSocket = null;

    try {// w w w  .  j  ava 2 s  .  c om
        tcpSocket = new ServerSocket(port);
        tcpSocket.setReuseAddress(true);

        udpSocket = new DatagramSocket(port);
        udpSocket.setReuseAddress(true);
        return true;
    } catch (IOException ex) {
        // denotes the port is in use
    } finally {
        if (tcpSocket != null) {
            try {
                tcpSocket.close();
            } catch (IOException e) {
                /* not to be thrown */
            }
        }

        if (udpSocket != null) {
            udpSocket.close();
        }
    }

    return false;
}

From source file:com.googlecode.jmxtrans.connections.DatagramSocketFactory.java

/**
 * Closes the socket./* www .  j ava  2 s  .  co m*/
 */
@Override
public void destroyObject(SocketAddress key, DatagramSocket socket) throws Exception {
    socket.close();
}

From source file:net.pms.network.UPNPHelper.java

/**
 * Send reply./*w ww  .ja  v  a 2 s . co  m*/
 *
 * @param host the host
 * @param port the port
 * @param msg the msg
 * @throws IOException Signals that an I/O exception has occurred.
 */
private static void sendReply(String host, int port, String msg) {
    DatagramSocket datagramSocket = null;

    try {
        datagramSocket = new DatagramSocket();
        InetAddress inetAddr = InetAddress.getByName(host);
        DatagramPacket dgmPacket = new DatagramPacket(msg.getBytes(), msg.length(), inetAddr, port);

        logger.trace(
                "Sending this reply [" + host + ":" + port + "]: " + StringUtils.replace(msg, CRLF, "<CRLF>"));

        datagramSocket.send(dgmPacket);
    } catch (Exception e) {
        logger.info(e.getMessage());
        logger.debug("Error sending reply", e);
    } finally {
        if (datagramSocket != null) {
            datagramSocket.close();
        }
    }
}

From source file:uk.co.ghosty.phonegap.plugins.WakeOnLan.java

@Override
public PluginResult execute(String action, JSONArray data, String callbackId) {
    // TODO Auto-generated method stub
    Log.d("WakeOnLan", "Calling plugin execute message");
    PluginResult result = null;/* w  ww .j  a  v a 2 s.  c o  m*/
    if (ACTION.equals(action)) {
        try {
            String macStr = data.getString(0);
            String ipStr = data.getString(1);

            byte[] macBytes = getMacBytes(macStr);
            byte[] bytes = new byte[6 + 16 * macBytes.length];

            for (int i = 0; i < 6; i++) {
                bytes[i] = (byte) 0xff;
            }
            for (int i = 6; i < bytes.length; i += macBytes.length) {
                System.arraycopy(macBytes, 0, bytes, i, macBytes.length);
            }

            InetAddress address = InetAddress.getByName(ipStr);
            DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, PORT);
            DatagramSocket socket = new DatagramSocket();
            socket.send(packet);
            socket.close();

            System.out.println("Wake-on-LAN packet sent.");
            result = new PluginResult(Status.OK, "Packet sent");
        } catch (Exception e) {
            result = new PluginResult(Status.IO_EXCEPTION);
            Log.e("WakeOnLan", "Exception thrown", e);
        }
    } else {
        result = new PluginResult(Status.INVALID_ACTION);
        Log.d("DirectoryListPlugin", "Invalid action : " + action + " passed");
    }
    return result;
}

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

public void passivateObject(Object key, Object object) throws Exception {
    ImmutableEndpoint ep = (ImmutableEndpoint) key;

    boolean keepSocketOpen = MapUtils.getBooleanValue(ep.getProperties(),
            UdpConnector.KEEP_SEND_SOCKET_OPEN_PROPERTY,
            ((UdpConnector) ep.getConnector()).isKeepSendSocketOpen());
    DatagramSocket socket = (DatagramSocket) object;

    if (!keepSocketOpen) {
        if (socket != null) {
            socket.close();
        }/* w ww.  j a va 2 s  .  c  o  m*/
    }
}

From source file:org.openhab.binding.wol.internal.WolBinding.java

private void sendWolPacket(WolBindingConfig config) {

    if (config == null) {
        logger.error("given parameter 'config' must not be null");
        return;//from  w  ww.j  a v  a 2s .c o m
    }

    InetAddress address = config.address;
    byte[] macBytes = config.macBytes;

    try {

        byte[] bytes = fillMagicBytes(macBytes);

        DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, PORT);

        DatagramSocket socket = new DatagramSocket();
        socket.send(packet);
        socket.close();

        logger.info("Wake-on-LAN packet sent [broadcastIp={}, macaddress={}]", address.getHostName(),
                String.valueOf(Hex.encodeHex(macBytes)));
    } catch (Exception e) {
        logger.error("Failed to send Wake-on-LAN packet [broadcastIp=" + address.getHostAddress()
                + ", macaddress=" + String.valueOf(Hex.encodeHex(macBytes)) + "]", e);
    }

}

From source file:org.springframework.integration.syslog.inbound.SyslogReceivingChannelAdapterTests.java

@Test
public void testUdp() throws Exception {
    SyslogReceivingChannelAdapterFactoryBean factory = new SyslogReceivingChannelAdapterFactoryBean(
            SyslogReceivingChannelAdapterFactoryBean.Protocol.udp);
    int port = SocketUtils.findAvailableUdpSocket(1514);
    factory.setPort(port);//w  w  w.  ja  v  a2 s  .co  m
    PollableChannel outputChannel = new QueueChannel();
    factory.setOutputChannel(outputChannel);
    factory.setBeanFactory(mock(BeanFactory.class));
    factory.afterPropertiesSet();
    factory.start();
    UdpSyslogReceivingChannelAdapter adapter = (UdpSyslogReceivingChannelAdapter) factory.getObject();
    Thread.sleep(1000);
    byte[] buf = "<157>JUL 26 22:08:35 WEBERN TESTING[70729]: TEST SYSLOG MESSAGE".getBytes("UTF-8");
    DatagramPacket packet = new DatagramPacket(buf, buf.length, new InetSocketAddress("localhost", port));
    DatagramSocket socket = new DatagramSocket();
    socket.send(packet);
    socket.close();
    Message<?> message = outputChannel.receive(10000);
    assertNotNull(message);
    assertEquals("WEBERN", message.getHeaders().get("syslog_HOST"));
    adapter.stop();
}

From source file:org.springframework.integration.syslog.inbound.SyslogReceivingChannelAdapterTests.java

@Test
public void testAsMapFalse() throws Exception {
    SyslogReceivingChannelAdapterFactoryBean factory = new SyslogReceivingChannelAdapterFactoryBean(
            SyslogReceivingChannelAdapterFactoryBean.Protocol.udp);
    int port = SocketUtils.findAvailableUdpSocket(1514);
    factory.setPort(port);//from  w w  w.  ja v  a 2  s  .c  om
    PollableChannel outputChannel = new QueueChannel();
    factory.setOutputChannel(outputChannel);
    factory.setBeanFactory(mock(BeanFactory.class));
    factory.afterPropertiesSet();
    factory.start();
    UdpSyslogReceivingChannelAdapter adapter = (UdpSyslogReceivingChannelAdapter) factory.getObject();
    DefaultMessageConverter defaultMessageConverter = new DefaultMessageConverter();
    defaultMessageConverter.setAsMap(false);
    adapter.setConverter(defaultMessageConverter);
    Thread.sleep(1000);
    byte[] buf = "<157>JUL 26 22:08:35 WEBERN TESTING[70729]: TEST SYSLOG MESSAGE".getBytes("UTF-8");
    DatagramPacket packet = new DatagramPacket(buf, buf.length, new InetSocketAddress("localhost", port));
    DatagramSocket socket = new DatagramSocket();
    socket.send(packet);
    socket.close();
    Message<?> message = outputChannel.receive(10000);
    assertNotNull(message);
    assertEquals("WEBERN", message.getHeaders().get("syslog_HOST"));
    assertEquals("<157>JUL 26 22:08:35 WEBERN TESTING[70729]: TEST SYSLOG MESSAGE",
            new String((byte[]) message.getPayload(), "UTF-8"));
    adapter.stop();
}

From source file:org.springframework.integration.syslog.inbound.SyslogReceivingChannelAdapterTests.java

@Test
public void testUdpRFC5424() throws Exception {
    SyslogReceivingChannelAdapterFactoryBean factory = new SyslogReceivingChannelAdapterFactoryBean(
            SyslogReceivingChannelAdapterFactoryBean.Protocol.udp);
    int port = SocketUtils.findAvailableUdpSocket(1514);
    factory.setPort(port);/*from  www .ja  va2s  .  c om*/
    PollableChannel outputChannel = new QueueChannel();
    factory.setOutputChannel(outputChannel);
    factory.setBeanFactory(mock(BeanFactory.class));
    factory.setConverter(new RFC5424MessageConverter());
    factory.afterPropertiesSet();
    factory.start();
    UdpSyslogReceivingChannelAdapter adapter = (UdpSyslogReceivingChannelAdapter) factory.getObject();
    Thread.sleep(1000);
    byte[] buf = ("<14>1 2014-06-20T09:14:07+00:00 loggregator d0602076-b14a-4c55-852a-981e7afeed38 DEA - "
            + "[exampleSDID@32473 iut=\\\"3\\\" eventSource=\\\"Application\\\" eventID=\\\"1011\\\"]"
            + "[exampleSDID@32473 iut=\\\"3\\\" eventSource=\\\"Application\\\" eventID=\\\"1011\\\"] Removing instance")
                    .getBytes("UTF-8");
    DatagramPacket packet = new DatagramPacket(buf, buf.length, new InetSocketAddress("localhost", port));
    DatagramSocket socket = new DatagramSocket();
    socket.send(packet);
    socket.close();
    @SuppressWarnings("unchecked")
    Message<Map<String, ?>> message = (Message<Map<String, ?>>) outputChannel.receive(10000);
    assertNotNull(message);
    assertEquals("loggregator", message.getPayload().get("syslog_HOST"));
    adapter.stop();
}

From source file:com.navercorp.pinpoint.collector.receiver.thrift.udp.UDPReceiverTest.java

@Test
public void sendSocketBufferSize() throws IOException {
    DatagramPacket datagramPacket = new DatagramPacket(new byte[0], 0, 0);

    DatagramSocket datagramSocket = new DatagramSocket();
    datagramSocket.connect(new InetSocketAddress(ADDRESS, PORT));

    datagramSocket.send(datagramPacket);
    datagramSocket.close();
}