Example usage for java.net DatagramSocket disconnect

List of usage examples for java.net DatagramSocket disconnect

Introduction

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

Prototype

public void disconnect() 

Source Link

Document

Disconnects the socket.

Usage

From source file:Main.java

public static void main(String args[]) {
    try {/*w ww. jav  a  2 s.  c om*/

        InetAddress ia = InetAddress.getByName("www.java2s.com");

        DatagramSocket ds = new DatagramSocket();

        byte buffer[] = "hello".getBytes();
        DatagramPacket dp = new DatagramPacket(buffer, buffer.length, ia, 80);

        ds.send(dp);
        ds.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:energy.usef.core.util.DateTimeUtil.java

private static synchronized String getUDPInfo(String message) {
    try {//from  w ww .  j  a  va 2s .c o  m
        LOGGER.debug("SENDING: {}", message);
        byte[] buf = message.getBytes();
        InetAddress address = InetAddress.getByName(serverIp);
        DatagramSocket socket = new DatagramSocket();
        socket.send(new DatagramPacket(buf, buf.length, address, port));
        DatagramPacket result = new DatagramPacket(new byte[PACKAGE_BUFFER], PACKAGE_BUFFER);
        socket.disconnect();
        socket.setSoTimeout(RESPONSE_TIMEOUT);
        socket.receive(result);
        socket.disconnect();
        socket.close();
        String resultStr = new String(result.getData()).trim();
        LOGGER.debug("RECEIVED: {} ", resultStr);
        errorCount = 0;
        return resultStr;
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
        errorCount++;
        if (errorCount >= MAX_ERROR_COUNT) {
            LOGGER.error("Unable to run simulation correctly.");
            System.exit(1);
        }
    }
    return null;
}

From source file:org.eclipse.smarthome.binding.wemo.discovery.WemoDiscoveryService.java

public void sendWemoDiscoveryMessage() {
    logger.debug("wemoDiscovery() is called!");
    try {/*w  w  w  .ja v a 2s . c om*/

        InetAddress localhost = InetAddress.getLocalHost();
        InetSocketAddress srcAddress = new InetSocketAddress(localhost, SSDP_SEARCH_PORT);

        InetSocketAddress dstAddress = new InetSocketAddress(InetAddress.getByName(SSDP_IP), SSDP_PORT);

        // Request-Packet-Constructor
        StringBuffer discoveryMessage = new StringBuffer();
        discoveryMessage.append("M-SEARCH * HTTP/1.1\r\n");
        discoveryMessage.append("HOST: " + SSDP_IP + ":" + SSDP_PORT + "\r\n");
        discoveryMessage.append("ST: upnp:rootdevice\r\n");
        discoveryMessage.append("MAN: \"ssdp:discover\"\r\n");
        discoveryMessage.append("MX: 5\r\n");
        discoveryMessage.append("\r\n");
        logger.trace("Request: {}", discoveryMessage.toString());
        byte[] discoveryMessageBytes = discoveryMessage.toString().getBytes();
        DatagramPacket discoveryPacket = new DatagramPacket(discoveryMessageBytes, discoveryMessageBytes.length,
                dstAddress);

        // Send multi-cast packet
        MulticastSocket multicast = null;
        try {
            multicast = new MulticastSocket(null);
            multicast.bind(srcAddress);
            logger.trace("Source-Address = '{}'", srcAddress);
            multicast.setTimeToLive(4);
            logger.debug("Send multicast request.");
            multicast.send(discoveryPacket);
        } finally {
            logger.trace("Multicast ends. Close connection.");
            multicast.disconnect();
            multicast.close();
        }

        // Response-Listener
        DatagramSocket wemoReceiveSocket = null;
        DatagramPacket receivePacket = null;
        try {
            wemoReceiveSocket = new DatagramSocket(SSDP_SEARCH_PORT);
            wemoReceiveSocket.setSoTimeout(TIMEOUT);
            logger.debug("Send datagram packet.");
            wemoReceiveSocket.send(discoveryPacket);

            while (true) {
                try {
                    receivePacket = new DatagramPacket(new byte[1536], 1536);
                    wemoReceiveSocket.receive(receivePacket);
                    final String message = new String(receivePacket.getData());
                    logger.trace("Received message: {}", message);

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            String label = "WeMo Device";
                            String wemoUDN = null;
                            String wemoLocation = null;
                            String wemoFriendlyName = null;
                            String wemoModelName = null;
                            ThingUID uid = null;

                            if (message != null) {
                                if (message.contains("Socket-1_0") || message.contains("Insight-1_0")
                                        || message.contains("Motion-1_0")
                                        || message.contains("Lightswitch-1_0")) {
                                    wemoUDN = StringUtils.substringBetween(message, "USN: uuid:",
                                            "::upnp:rootdevice");
                                    logger.debug("Wemo device with UDN '{}' found", wemoUDN);
                                    wemoLocation = StringUtils.substringBetween(message, "LOCATION: ",
                                            "/setup.xml");
                                    if (wemoLocation != null) {
                                        try {
                                            int timeout = 5000;
                                            String response = HttpUtil.executeUrl("GET",
                                                    wemoLocation + "/setup.xml", timeout);
                                            wemoFriendlyName = StringUtils.substringBetween(response,
                                                    "<friendlyName>", "</friendlyName>");
                                            logger.debug("Wemo device '{}' found at '{}'", wemoFriendlyName,
                                                    wemoLocation);
                                            wemoModelName = StringUtils.substringBetween(response,
                                                    "<modelName>", "</modelName>");
                                            logger.trace("Wemo device '{}' has model name '{}'",
                                                    wemoFriendlyName, wemoModelName);
                                            label = "Wemo" + wemoModelName;

                                            switch (wemoModelName) {
                                            case "Socket":
                                                logger.debug(
                                                        "Creating ThingUID for device model '{}' with UDN '{}'",
                                                        wemoModelName, wemoUDN);
                                                uid = new ThingUID(WEMO_SOCKET_TYPE_UID, wemoUDN);

                                                break;
                                            case "Insight":
                                                logger.trace(
                                                        "Creating ThingUID for device model '{}' with UDN '{}'",
                                                        wemoModelName, wemoUDN);
                                                uid = new ThingUID(WEMO_INSIGHT_TYPE_UID, wemoUDN);
                                                break;
                                            case "LightSwitch":
                                                logger.trace(
                                                        "Creating ThingUID for device model '{}' with UDN '{}'",
                                                        wemoModelName, wemoUDN);
                                                uid = new ThingUID(WEMO_LIGHTSWITCH_TYPE_UID, wemoUDN);
                                                break;
                                            case "Motion":
                                                logger.trace(
                                                        "Creating ThingUID for device model '{}' with UDN '{}'",
                                                        wemoModelName, wemoUDN);
                                                uid = new ThingUID(WEMO_MOTION_TYPE_UID, wemoUDN);
                                                break;
                                            }
                                            Map<String, Object> properties = new HashMap<>(4);
                                            properties.put(UDN, wemoUDN);
                                            properties.put(LOCATION, wemoLocation);

                                            DiscoveryResult result = DiscoveryResultBuilder.create(uid)
                                                    .withProperties(properties).withLabel(label).build();
                                            thingDiscovered(result);

                                        } catch (Exception te) {
                                            logger.error("Could not discover WeMo device", te);
                                        }
                                    }
                                }
                            }
                        }
                    }).start();

                } catch (SocketTimeoutException e) {
                    logger.debug("Message receive timed out.");
                    break;
                }
            }
        } finally {
            if (wemoReceiveSocket != null) {
                wemoReceiveSocket.disconnect();
                wemoReceiveSocket.close();
            }
        }

    } catch (Exception e) {
        logger.error("Could not send Wemo device discovery", e);
    }

}

From source file:org.rifidi.emulator.io.comm.ip.udp.UDPCommunicationTest.java

/**
 * Tests turning on the UDPCommunication while it is off.
 * //from  w w  w  .  ja v  a2  s  .  c om
 *  
 */
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.rifidi.emulator.io.comm.ip.udp.UDPOnCommunicationPowerState.java

/**
 * Disconnects the socket. Doing this will also kill any threads that are
 * running that are using this socket. In UDP sockets close is tightly bound
 * to a disconnect and thus the socket is also closed as well.
 *///from  w  w  w  .  j  a va 2s . c  o m
public void disconnect(UDPCommunication dconnudpComm) {

    DatagramSocket dgs = dconnudpComm.getDatagramSocket();
    boolean outputTest = dconnudpComm.isOutputOnly();

    if (outputTest) {
        /* If it is output only then the disconnect works fine */
        dgs.disconnect();
    } else {
        /* TODO Need to resolve bug in UDPCommunication where
         * the disconnect hangs when there is both an incoming
         * and outgoing message handler
         */
        logger.warn("UDPCommunication was closed but not disconnected"
                + " due to UDPIncoming Handler Bug - results may vary");
    }

    /* close the datagram socket */
    dgs.close();
}

From source file:org.rifidi.emulator.reader.alien.heartbeat.HeartbeatController.java

/**
 * Send out a heartbeat// ww w.j  a  v  a  2 s  . co  m
 */
private void broadcast() {
    String retString = "<Alien-RFID-Reader-Heartbeat>\n" + "  <ReaderName>Alien RFID Reader</ReaderName>\n"
            + "  <ReaderType>Alien RFID Tag Reader, Model: ALR-9800(Four Antenna / Multi-Protocol / 915 Mhz)"
            + "</ReaderType>\n" + "  <IPAddress>" + asr.getCommandIP() + "</IPAddress>\n" + "  <CommandPort>"
            + asr.getCommandPort() + "</CommandPort>\n" + "  <HeartbeatTime>" + this.timeInMs / 1000
            + "</HeartbeatTime>\n" + "  <MACAddress>00:00:00:00:00:00</MACAddress>\n"
            + "</Alien-RFID-Reader-Heartbeat>\n";

    try {
        logger.debug("Attempting to send heartbeat...");
        DatagramSocket sock = new DatagramSocket(bindingPort);
        InetAddress ia = InetAddress.getByName(broadcastAddr);
        sock.setBroadcast(true);
        DatagramPacket p = new DatagramPacket(retString.getBytes(), retString.getBytes().length, ia,
                broadcastPort);
        sock.send(p);
        sock.disconnect();
        sock.close();
    } catch (SocketException e) {
        e.printStackTrace();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}