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.analytics.common.jmx.agent.JmxAgentWebInterface.java

/**
 * Test the availability of the DataPublisher by
 * trying to connect to it (credentials are not checked)
 *
 * @return : whether the test was successful or not
 *//*from   w  w w. ja  v  a  2 s .c om*/
public boolean testDataPublisherAvailability(String connectionType, String url, int port) {

    //check for tcp and ssl port availability
    if (connectionType.equalsIgnoreCase("tcp://") || connectionType.equalsIgnoreCase("ssl://")) {

        DatagramSocket ds = null;

        try {
            ds = new DatagramSocket(port);
            ds.setReuseAddress(true);

            return true;
        } catch (IOException e) {
            log.error(e);
        } finally {
            if (ds != null) {
                ds.close();
            }
        }
    }

    //check for http and https port availability
    if (connectionType.equalsIgnoreCase("http://") || connectionType.equalsIgnoreCase("https://")) {

        Socket socket = null;

        try {
            socket = new Socket();
            socket.setReuseAddress(true);

            SocketAddress sa = new InetSocketAddress(url, port);
            socket.connect(sa);
            return true;
        } catch (IOException e) {
            log.error(e);
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    //do nothing
                }
            }
        }
    }

    return false;
}

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 www.ja  v  a 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.openchaos.android.fooping.service.PingService.java

private void sendMessage(final JSONObject json) {
    boolean encrypt = prefs.getBoolean("SendAES", false);
    boolean compress = prefs.getBoolean("SendGZIP", false);
    String exchangeHost = prefs.getString("ExchangeHost", null);
    int exchangePort = Integer.valueOf(prefs.getString("ExchangePort", "-1"));

    if (encrypt) {
        if (skeySpec == null) {
            try {
                skeySpec = new SecretKeySpec(MessageDigest.getInstance("SHA-256")
                        .digest(prefs.getString("ExchangeKey", null).getBytes("US-ASCII")), "AES");
            } catch (Exception e) {
                Log.e(tag, e.toString());
                e.printStackTrace();//from  www.j a  va  2 s  .  com
            }
        }

        if (cipher == null) {
            try {
                cipher = Cipher.getInstance("AES/CFB8/NoPadding");
            } catch (Exception e) {
                Log.e(tag, e.toString());
                e.printStackTrace();
            }
        }

        if (skeySpec == null || cipher == null) {
            Log.e(tag, "Encryption requested but not available");
            throw new AssertionError();
        }
    }

    if (exchangeHost == null || exchangePort <= 0 || exchangePort >= 65536) {
        Log.e(tag, "Invalid server name or port");
        throw new AssertionError();
    }

    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        CipherOutputStream cos = null;
        GZIPOutputStream zos = null;

        // TODO: send protocol header to signal compression & encryption

        if (encrypt) {
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            cos = new CipherOutputStream(baos, cipher);

            // write iv block
            baos.write(cipher.getIV());
        }

        final byte[] message = new JSONArray().put(json).toString().getBytes();

        if (compress) {
            zos = new GZIPOutputStream((encrypt) ? (cos) : (baos));
            zos.write(message);
            zos.finish();
            zos.close();
            if (encrypt) {
                cos.close();
            }
        } else if (encrypt) {
            cos.write(message);
            cos.close();
        } else {
            baos.write(message);
        }

        baos.flush();
        final byte[] output = baos.toByteArray();
        baos.close();

        // path MTU is the actual limit here, not only local MTU
        // TODO: make packet fragmentable (clear DF flag)
        if (output.length > 1500) {
            Log.w(tag, "Message probably too long: " + output.length + " bytes");
        }

        DatagramSocket socket = new DatagramSocket();
        // socket.setTrafficClass(0x04 | 0x02); // IPTOS_RELIABILITY | IPTOS_LOWCOST
        socket.send(
                new DatagramPacket(output, output.length, InetAddress.getByName(exchangeHost), exchangePort));
        socket.close();
        Log.d(tag, "message sent: " + output.length + " bytes (raw: " + message.length + " bytes)");
    } catch (Exception e) {
        Log.e(tag, e.toString());
        e.printStackTrace();
    }
}

From source file:org.opennms.netmgt.syslogd.SyslogdLoadIT.java

public void doTestSyslogReceiver() throws Exception {
    final int eventCount = 100;

    List<Integer> foos = new ArrayList<Integer>();

    for (int i = 0; i < eventCount; i++) {
        int eventNum = Double.valueOf(Math.random() * 10000).intValue();
        foos.add(eventNum);//from  ww  w  .  j  a  v  a2 s .  co m
    }

    m_eventCounter.setAnticipated(eventCount);

    String testPduFormat = "2010-08-19 localhost foo%d: load test %d on tty1";
    SyslogClient sc = new SyslogClient(null, 10, SyslogClient.LOG_USER, addr("127.0.0.1"));

    // Test by sending over a java.net socket
    final DatagramSocket socket = new DatagramSocket();
    System.err.println("Starting to send packets");
    final long start = System.currentTimeMillis();
    for (int i = 0; i < eventCount; i++) {
        int foo = foos.get(i);
        DatagramPacket pkt = sc.getPacket(SyslogClient.LOG_DEBUG, String.format(testPduFormat, foo, foo));
        socket.send(pkt);
    }
    socket.close();

    /*
    // Test by sending over an NIO channel
    SocketAddress address = new InetSocketAddress(InetAddressUtils.getLocalHostAddress(), SyslogClient.PORT);
    final DatagramChannel channel = DatagramChannel.open();
    final ByteBuffer buffer = ByteBuffer.allocate(SyslogReceiverNioThreadPoolImpl.MAX_PACKET_SIZE);
    buffer.clear();
    System.err.println("Starting to send packets");
    final long start = System.currentTimeMillis();
    for (int i = 0; i < eventCount; i++) {
    int foo = foos.get(i);
    buffer.put(SyslogClient.getPacketPayload(SyslogClient.LOG_USER, null, SyslogClient.LOG_DEBUG, String.format(testPduFormat, foo, foo)));
    buffer.flip();
    channel.send(buffer, address);
    buffer.clear();
    }
    channel.close();
    */

    long mid = System.currentTimeMillis();
    System.err.println(String.format("Sent %d packets in %d milliseconds", eventCount, mid - start));

    m_eventCounter.waitForFinish(30000);
    long end = System.currentTimeMillis();

    System.err.println(
            String.format("Events expected: %d, events received: %d", eventCount, m_eventCounter.getCount()));
    final long total = (end - start);
    final double eventsPerSecond = (eventCount * 1000.0 / total);
    System.err.println(String.format("total time: %d, wait time: %d, events per second: %8.4f", total,
            (end - mid), eventsPerSecond));

    assertEquals(eventCount, m_eventCounter.getCount());
}

From source file:net.sourceforge.vulcan.ant.receiver.UdpEventSource.java

@Override
public void run() {
    final DatagramSocket socket = openSocket();
    active = true;/* ww  w .j a  v  a 2  s . co m*/

    synchronized (this) {
        notifyAll();
    }

    final byte[] buffer = new byte[8192];

    try {
        final DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
        while (active) {
            try {
                socket.receive(packet);

                final AntEventSummary summary = deserialize(packet.getData());

                fireEvent(summary);
            } catch (SocketTimeoutException e) {
                continue;
            } catch (Exception e) {
                handleException(e);
            }
        }
    } finally {
        socket.close();
    }
}

From source file:poisondog.net.udp.DatagramMission.java

public DatagramResponse execute(DatagramParameter parameter) throws IOException {
    DatagramSocket socket = new DatagramSocket(null);
    socket.setReuseAddress(true);//w  ww .  ja v a 2  s.  c o  m

    socket.setBroadcast(parameter.getBroadcast());
    if (parameter.getTimeout() > 0)
        socket.setSoTimeout(parameter.getTimeout());
    String data = IOUtils.toString(parameter.getInputStream());
    DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length());
    packet.setAddress(InetAddress.getByName(parameter.getHost()));
    packet.setPort(parameter.getPort());
    socket.send(packet);

    DatagramResponse response = new DatagramResponse(parameter.getResponseLength());
    DatagramPacket responsePacket = new DatagramPacket(response.getContent(), response.getContent().length);
    socket.receive(responsePacket);
    response.setAddress(responsePacket.getAddress().getHostAddress());
    response.setPacketLength(responsePacket.getLength());
    socket.close();
    return response;
}

From source file:com.clustercontrol.notify.util.SendSyslog.java

private void sendUdpMsg(InetAddress ipAddress, int port, String msg) throws IOException {
    DatagramSocket soc = null;
    try {/*from  w w  w . ja  v  a2 s. c  o  m*/
        // ??????
        soc = new DatagramSocket(); // ??
        DatagramPacket sendPacket = null; // 

        sendPacket = new DatagramPacket(msg.getBytes(), msg.getBytes().length, ipAddress, port);
        soc.send(sendPacket);
    } finally {
        if (soc != null) {
            soc.close();
        }
    }
}

From source file:org.psit.transwatcher.TransWatcher.java

private String connectAndGetCardIP() {
    DatagramSocket clientSocket = null, serverSocket = null;

    try {/*  ww  w. j  a v  a 2s . com*/
        String broadcastIP = getBroadcastIP();
        setState(broadcastIP == null ? State.NO_WIFI : State.SEARCHING_CARD);
        notifyMessage("BroadcastIP: " + broadcastIP);

        // send out broadcast
        clientSocket = new DatagramSocket(58255);
        InetAddress IPAddress = InetAddress.getByName(broadcastIP);
        byte[] sendData = "".getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 55777);
        clientSocket.send(sendPacket);
        clientSocket.close();

        serverSocket = new DatagramSocket(58255);
        byte[] receiveData = new byte[256];
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        serverSocket.setSoTimeout(3000);
        serverSocket.receive(receivePacket);
        serverSocket.close();

        notifyMessage("Packet received: " + new String(receiveData));
        if (new String(receivePacket.getData()).indexOf("Transcend WiFiSD") >= 0)
            return receivePacket.getAddress().getHostAddress();
    } catch (Exception ex) {
        notifyMessage("Card handshake unsuccessful. ");
        notifyException(ex);
    } finally {
        if (clientSocket != null)
            clientSocket.close();
        if (serverSocket != null)
            serverSocket.close();
    }
    return null;
}

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

private int dtnResourcesRequest(Node node) throws WSIAdapterException, IOException {
    int requestMsgId = UNDEFINED_COAP_MESSAGE_ID; // TODO: ??? we will use the packetID as a message ID to return.
    String proxyAddress = getProxyAddress(node);
    if (proxyAddress != null) {
        int packetID = UNDEFINED_COAP_MESSAGE_ID;
        do { //while loop to avoid a packetID that exists in the array that is to be ignored!
            packetID = random.nextInt(65535) + 1;
        } while (timedOut_DTN_CoapMessageIDsList.contains(Integer.valueOf(packetID))
                || packetID == UNDEFINED_COAP_MESSAGE_ID);

        String msgString = Integer.toString(packetID) + "#" + node.getId() + "#" + RESOURCE_REQ + "#wkc";
        byte[] msgBytes = new byte[Constants.DTN_MESSAGE_SIZE];
        msgBytes = msgString.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(msgBytes, msgBytes.length,
                InetAddress.getByName(proxyAddress), Constants.PROXY_UDPFORWARDER_PORT);
        DatagramSocket clientSocket = new DatagramSocket();
        clientSocket.send(sendPacket);/*from  ww w . ja  va  2s.c  om*/
        clientSocket.close();
        requestMsgId = packetID;
        logger.info("Sent Request: " + msgString);
    } else {
        logger.warn("No available proxy for Node " + node.getId() + " is found");
        throw new WSIAdapterException("No available proxy for Node " + node.getId() + " is found");
    }
    return requestMsgId;
}

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

private int dtnObservationRequest(Node node, Resource resource) throws VitroGatewayException, IOException {
    int requestMsgId = UNDEFINED_COAP_MESSAGE_ID; // TODO: ??? we will use the packetID as a message ID to return.
    String proxyAddress = getProxyAddress(node);
    if (proxyAddress != null) {
        String moteUriResource = "";
        if (MoteResource.containsValue(resource)) {
            //moteUriResource += MoteResource.getMoteUriResource(resource);
            String theResourceName = MoteResource.getMoteUriResource(resource);
            if (theResourceName == null) {
                logger.error("unsupported resource");
                return UNDEFINED_COAP_MESSAGE_ID;
            }/*w ww  .ja v  a2  s  .co m*/
            // FOR TCS adapter, we prefer the TEMPERATURE_TCS
            // FOR WLAB and HAI we prefer the TEMPERATURE_ALT
            // we do this check because the getMoteUriResource is making a reverse lookup in the hashmap (where two keys point to the same resource)
            if (theResourceName.compareToIgnoreCase(MoteResource.TEMPERATURE_TCS) == 0) {
                theResourceName = MoteResource.TEMPERATURE_ALT;
            }
            moteUriResource += theResourceName;

            int packetID = UNDEFINED_COAP_MESSAGE_ID;
            do { //while loop to avoid a packetID that exists in the array that is to be ignored!
                packetID = random.nextInt(65535) + 1;
            } while (timedOut_DTN_CoapMessageIDsList.contains(Integer.valueOf(packetID))
                    || packetID == UNDEFINED_COAP_MESSAGE_ID);

            String msgString = packetID + "#" + node.getId() + "#" + RESOURCE_REQ + "#" + moteUriResource;
            byte[] msgBytes = new byte[Constants.DTN_MESSAGE_SIZE];
            msgBytes = msgString.getBytes();
            DatagramPacket sendPacket = new DatagramPacket(msgBytes, msgBytes.length,
                    InetAddress.getByName(proxyAddress), Constants.PROXY_UDPFORWARDER_PORT);
            DatagramSocket clientSocket = new DatagramSocket();
            clientSocket.send(sendPacket);
            clientSocket.close();
            requestMsgId = packetID;
            logger.info("Sent Request: " + msgString);
        } else {
            logger.warn("No resource mapping for Node " + node.getId() + " and Resource " + resource.getName());
            throw new WSIAdapterException(
                    "No resource mapping for Node " + node.getId() + " and Resource " + resource.getName());
        }
    } else {
        logger.warn("No available proxy for Node " + node.getId() + " is found");
        throw new WSIAdapterException("No available proxy for Node " + node.getId() + " is found");
    }
    return requestMsgId;
}