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:vmTools.java

private String callOvnmanager(String node, String action) {
    String result = "";
    DatagramSocket socket = null;
    int serverPort = 9999;
    DatagramPacket packet2Send;/*w w w  .  j  av  a 2  s. co  m*/
    DatagramPacket receivedPacket;
    InetAddress theServerAddress;
    byte[] outBuffer;
    byte[] inBuffer;
    inBuffer = new byte[65536];
    outBuffer = new byte[8192];
    /*
    if (this.user == null) {
    this.user = "admin";
    }*/

    try {
        HttpSession session = RuntimeAccess.getInstance().getSession();

        String sessionUser = (String) session.getAttribute("User");
        if (sessionUser == null) {
            sessionUser = "administrator";
        }

        JSONObject joCmd = new JSONObject();
        JSONObject joAction = new JSONObject(action);
        joCmd.put("sender", sessionUser);
        joCmd.put("target", "VM");
        joCmd.put("node", node);
        joCmd.put("action", joAction);
        String output = joCmd.toString();

        socket = new DatagramSocket();
        String actionName = joAction.get("name").toString();
        /*if (actionName.equals("migrate")) {
        socket.setSoTimeout(600000);
        } else {
        socket.setSoTimeout(60000);
        }*/
        socket.setSoTimeout(60000);

        InetAddress serverInet = InetAddress.getByName("localhost");
        socket.connect(serverInet, serverPort);
        outBuffer = output.getBytes();
        packet2Send = new DatagramPacket(outBuffer, outBuffer.length, serverInet, serverPort);

        try {
            // send the data
            socket.send(packet2Send);
            receivedPacket = new DatagramPacket(inBuffer, inBuffer.length);
            socket.receive(receivedPacket);
            // the server response is...
            result = new String(receivedPacket.getData(), 0, receivedPacket.getLength());
            session.setAttribute("LastActive", System.currentTimeMillis());
        } catch (Exception excep) {
            String msg = excep.getMessage();
            //String msg = excep.toString();
            joCmd.remove("action");
            joAction.put("result", "Error:" + msg);
            joCmd.put("action", joAction);
            result = joCmd.toString();
        }
        socket.close();

    } catch (Exception e) {
        log(ERROR, "callOvnmanager", e);
        return e.toString();
    }
    return result;
}

From source file:serverTools.java

private String callOvnmanager(String node, String action) {
    String result = "";
    DatagramSocket socket = null;
    int serverPort = 9999;
    DatagramPacket packet2Send;/*w w  w. j a  v  a 2 s  . c  om*/
    DatagramPacket receivedPacket;
    InetAddress theServerAddress;
    byte[] outBuffer;
    byte[] inBuffer;
    //inBuffer = new byte[8192];
    //outBuffer = new byte[8192];
    inBuffer = new byte[65536];
    outBuffer = new byte[8192];

    try {
        HttpSession session = RuntimeAccess.getInstance().getSession();
        String sessionUser = (String) session.getAttribute("User");
        if (sessionUser == null) {
            sessionUser = "administrator";
        }

        JSONObject joAction = new JSONObject(action);
        JSONObject joCmd = new JSONObject();
        joCmd.put("sender", sessionUser);
        joCmd.put("target", "NODE");
        joCmd.put("node", node);
        joCmd.put("action", joAction);
        String output = joCmd.toString();

        socket = new DatagramSocket();
        // set timeout
        String actionName = joAction.get("name").toString();
        if (actionName.equals("add")) {
            socket.setSoTimeout(90000);
        } else if (actionName.equals("connect")) {
            socket.setSoTimeout(60000);
        } else {
            socket.setSoTimeout(60000);
        }
        InetAddress serverInet = InetAddress.getByName("localhost");
        socket.connect(serverInet, serverPort);
        outBuffer = output.getBytes();
        packet2Send = new DatagramPacket(outBuffer, outBuffer.length, serverInet, serverPort);
        receivedPacket = new DatagramPacket(inBuffer, inBuffer.length);

        try {
            // send the data
            socket.send(packet2Send);
            // receive reply            
            socket.receive(receivedPacket);
            // the server reply is...
            result = new String(receivedPacket.getData(), 0, receivedPacket.getLength());
            session.setAttribute("LastActive", System.currentTimeMillis());
        } catch (Exception excep) {
            String msg = excep.getMessage();
            //String msg = excep.toString();
            joCmd.remove("action");
            joAction.put("result", "Error:" + msg);
            joCmd.put("action", joAction);
            result = joCmd.toString();
        }
        socket.close();

    } catch (Exception e) {
        log(ERROR, "callOvnmanager", e);
        return e.toString();
    }
    return result;
}

From source file:vitro.vgw.wsiadapter.WSIAdapterCoap.java

/**
 * WSIAdapter interface/*from   w  ww .j  av a 2s. c om*/
 */

public List<Node> getAvailableNodeList() throws WSIAdapterException {

    logger.info("Getting available nodes...");

    nodesList = new ArrayList<Node>();

    List<String> wsnProxyList = new LinkedList<String>();
    wsnProxyList.add(Network.WLAB_OFFICE_PROXY_ADDRESS);
    wsnProxyList.add(Network.WLAB_LAB_PROXY_ADDRESS);

    DatagramSocket serverSocket = null;
    DatagramSocket clientSocket = null;
    String cmdString = "route";

    for (int i = 0; i < wsnProxyList.size(); i++) {
        try {
            serverSocket = new DatagramSocket(Constants.UDPSHELL_VGW_PORT);

            String hostProxyString = wsnProxyList.get(i);
            InetAddress hostProxy = InetAddress.getByName(hostProxyString);

            clientSocket = new DatagramSocket();
            byte[] bufCmd = new byte[10];
            bufCmd = cmdString.getBytes();
            DatagramPacket outcomingPacket = new DatagramPacket(bufCmd, bufCmd.length, hostProxy,
                    Constants.PROXY_UDPFORWARDER_PORT);
            clientSocket.send(outcomingPacket);

            boolean otherPackets = false;

            serverSocket.setSoTimeout(Constants.PROXY_RESPONSE_TIMEOUT);
            logger.info("Quering " + hostProxyString);
            try {
                byte[] bufAck = new byte[10];
                DatagramPacket ackPacket = new DatagramPacket(bufAck, bufAck.length);
                serverSocket.receive(ackPacket);
                String ackString = new String(ackPacket.getData()).trim();
                if (ackString.equals("ack")) {
                    otherPackets = true;
                }
            } catch (SocketTimeoutException e) {
                logger.warn(e.getMessage());
            }

            serverSocket.setSoTimeout(0);

            while (otherPackets) {
                try {
                    byte[] bufIncoming = new byte[1000];
                    DatagramPacket incomingPacket = new DatagramPacket(bufIncoming, bufIncoming.length);
                    serverSocket.receive(incomingPacket);
                    String currentNodeIP = new String(incomingPacket.getData()).trim();
                    if (!currentNodeIP.equals("end")) {
                        logger.info("Node: " + currentNodeIP);
                        nodesList.add(new Node(currentNodeIP));
                    } else {
                        otherPackets = false;
                        logger.info("No other nodes from " + hostProxyString);
                    }
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }
            }

        } catch (UnknownHostException e) {
            logger.warn(e.getMessage() + " is not reachable.");
        } catch (SocketException e) {
            logger.error(e.getMessage());
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            if (serverSocket != null) {
                serverSocket.close();
            }
            if (clientSocket != null) {
                clientSocket.close();
            }
        }
    }

    return nodesList;
}

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

public void sendWemoDiscoveryMessage() {
    logger.debug("wemoDiscovery() is called!");
    try {/* www  .j a  v a 2  s  .c o m*/

        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);
    }

}