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:com.clustercontrol.hinemosagent.util.AgentConnectUtil.java

/**
 * [Topic] getTopic?????UDP???/*from   w  w w .j  a  v  a  2 s.  c o  m*/
 * @param facilityId
 */
private static void awakeAgent(String facilityId) {
    String ipAddress = "";
    Integer port = 24005;
    m_log.debug("awakeAgent facilityId=" + facilityId);
    try {
        NodeInfo info = NodeProperty.getProperty(facilityId);
        ipAddress = info.getAvailableIpAddress();
        port = info.getAgentAwakePort();
    } catch (FacilityNotFound e) {
        m_log.debug(e.getMessage(), e);
        return;
    } catch (Exception e) {
        m_log.warn("awakeAgent facilityId=" + facilityId + " " + e.getClass().getSimpleName() + ", "
                + e.getMessage(), e);
        return;
    }
    if (port < 1 || 65535 < port) {
        m_log.info("awakeAgent : invalid port " + port + "(" + facilityId + ")");
    }
    m_log.debug("awakeAgent ipaddress=" + ipAddress);

    final int BUFSIZE = 1;
    byte[] buf = new byte[BUFSIZE];
    buf[0] = 1;
    InetAddress sAddr;
    try {
        sAddr = InetAddress.getByName(ipAddress);
    } catch (UnknownHostException e) {
        m_log.warn("awakeAgent facilityId=" + facilityId + " " + e.getClass().getSimpleName() + ", "
                + e.getMessage(), e);
        return;
    }
    DatagramPacket sendPacket = new DatagramPacket(buf, BUFSIZE, sAddr, port);
    DatagramSocket soc = null;
    try {
        soc = new DatagramSocket();
        soc.send(sendPacket);
    } catch (SocketException e) {
        m_log.warn("awakeAgent facilityId=" + facilityId + " " + e.getClass().getSimpleName() + ", "
                + e.getMessage(), e);
    } catch (IOException e) {
        m_log.warn("awakeAgent facilityId=" + facilityId + " " + e.getClass().getSimpleName() + ", "
                + e.getMessage(), e);
    } finally {
        if (soc != null) {
            soc.close();
        }
    }
}

From source file:org.midonet.util.netty.TestServerFrontEndUPD.java

private DatagramPacket sendMSG(byte[] msg, int port) throws Exception {
    DatagramSocket clientSocket = new DatagramSocket();
    InetAddress IPAddress = InetAddress.getByName("localhost");
    DatagramPacket sendPacket = new DatagramPacket(msg, msg.length, IPAddress, port);
    clientSocket.send(sendPacket);// w  w w.ja v  a  2  s  .  c  o  m
    clientSocket.close();
    return sendPacket;
}

From source file:org.springframework.integration.ip.udp.DatagramPacketSendingHandlerTests.java

@Test
@Ignore/*from  w ww  . j  a  va 2s . c  om*/
public void verifySendMulticastWithAcks() throws Exception {

    final List<Integer> openPorts = SocketUtils.findAvailableUdpSockets(SocketUtils.getRandomSeedPort(), 2);

    final int testPort = openPorts.get(0);
    final int ackPort = openPorts.get(1);

    final String multicastAddress = "225.6.7.8";
    final String payload = "foobar";
    final CountDownLatch latch1 = new CountDownLatch(2);
    final CountDownLatch latch2 = new CountDownLatch(2);
    Runnable catcher = new Runnable() {
        public void run() {
            try {
                byte[] buffer = new byte[1000];
                DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length);
                MulticastSocket socket = new MulticastSocket(testPort);
                InetAddress group = InetAddress.getByName(multicastAddress);
                socket.joinGroup(group);
                latch1.countDown();
                LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " waiting for packet");
                socket.receive(receivedPacket);
                socket.close();
                byte[] src = receivedPacket.getData();
                int length = receivedPacket.getLength();
                int offset = receivedPacket.getOffset();
                byte[] dest = new byte[6];
                System.arraycopy(src, offset + length - 6, dest, 0, 6);
                assertEquals(payload, new String(dest));
                LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " received packet");
                DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper();
                mapper.setAcknowledge(true);
                mapper.setLengthCheck(true);
                Message<byte[]> message = mapper.toMessage(receivedPacket);
                Object id = message.getHeaders().get(IpHeaders.ACK_ID);
                byte[] ack = id.toString().getBytes();
                DatagramPacket ackPack = new DatagramPacket(ack, ack.length,
                        new InetSocketAddress("localHost", ackPort));
                DatagramSocket out = new DatagramSocket();
                out.send(ackPack);
                out.close();
                latch2.countDown();
            } catch (Exception e) {
                noMulticast = true;
                latch1.countDown();
                e.printStackTrace();
            }
        }
    };
    Executor executor = Executors.newFixedThreadPool(2);
    executor.execute(catcher);
    executor.execute(catcher);
    latch1.await(3000, TimeUnit.MILLISECONDS);
    if (noMulticast) {
        return;
    }
    MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(multicastAddress, testPort,
            true, true, "localhost", ackPort, 500000);
    handler.setMinAcksForSuccess(2);
    handler.handleMessage(MessageBuilder.withPayload(payload).build());
    assertTrue(latch2.await(10000, TimeUnit.MILLISECONDS));
    handler.shutDown();
}

From source file:tubessister.SenderR.java

public void run() {
    System.out.println("Sender Running ");
    try {//from w w  w.j a va 2 s . c o  m
        InetAddress IPAddress = InetAddress.getByName(targetAddress);
        DatagramSocket datagramSocket = new DatagramSocket();
        ReliableSender ReliableSender = new ReliableSender(datagramSocket);
        byte[] sendData = message.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, targetPort);
        ReliableSender.send(sendPacket);
        datagramSocket.close();
    } catch (UnknownHostException ex) {
        System.out.println("Unknown Host Exception");
    } catch (SocketException ex) {
        System.out.println("Socket  Exception");
    } catch (IOException ex) {
        System.out.println("IO Exception");
    }
    System.out.println("Send finished");
}

From source file:org.shept.util.Monitor.java

/**
 * Send a simple 'Keep Alive' Datagram to the receiver
 *//*from ww  w .j  ava 2 s .c o  m*/
public Boolean keepAlive() {
    try {
        InetAddress adr = InetAddress.getByName(hostname);
        byte[] data = sendMsg.getBytes();
        DatagramSocket socket = new DatagramSocket();
        DatagramPacket pack = new DatagramPacket(data, data.length, adr, hostPort);
        socket.setSoTimeout(msecsSendTimeout);
        socket.send(pack);
        socket.close();
        return true;
    } catch (Exception ex) {
        return false;
    }
}

From source file:tubessister.Sender.java

public void run() {
    //System.out.println("Sender Running " );
    try {//from w  w  w . ja v a 2s  .  c  om
        InetAddress IPAddress = InetAddress.getByName(targetAddress);
        DatagramSocket datagramSocket = new DatagramSocket();
        UnreliableSender unreliableSender = new UnreliableSender(datagramSocket);
        byte[] sendData = message.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, targetPort);
        unreliableSender.send(sendPacket);
        datagramSocket.close();
    } catch (UnknownHostException ex) {
        System.out.println("Unknown Host Exception");
    } catch (SocketException ex) {
        System.out.println("Socket  Exception");
    } catch (IOException ex) {
        System.out.println("IO Exception");
    }
    System.out.println("Send finished");
}

From source file:org.springframework.integration.ip.udp.DatagramPacketSendingHandlerTests.java

@Test
public void verifySend() throws Exception {
    final int testPort = SocketUtils.findAvailableUdpSocket();
    byte[] buffer = new byte[8];
    final DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length);
    final CountDownLatch latch = new CountDownLatch(1);
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            try {
                DatagramSocket socket = new DatagramSocket(testPort);
                socket.receive(receivedPacket);
                latch.countDown();//from w w  w .  j  ava 2s . c  om
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    Thread.sleep(1000);
    UnicastSendingMessageHandler handler = new UnicastSendingMessageHandler("localhost", testPort);
    String payload = "foo";
    handler.handleMessage(MessageBuilder.withPayload(payload).build());
    assertTrue(latch.await(3000, TimeUnit.MILLISECONDS));
    byte[] src = receivedPacket.getData();
    int length = receivedPacket.getLength();
    int offset = receivedPacket.getOffset();
    byte[] dest = new byte[length];
    System.arraycopy(src, offset, dest, 0, length);
    assertEquals(payload, new String(dest));
    handler.shutDown();
}

From source file:org.springframework.integration.ip.udp.DatagramPacketSendingHandlerTests.java

@Test
public void verifySendWithAck() throws Exception {

    final List<Integer> openPorts = SocketUtils.findAvailableUdpSockets(SocketUtils.getRandomSeedPort(), 2);

    final int testPort = openPorts.get(0);
    final int ackPort = openPorts.get(1);

    byte[] buffer = new byte[1000];
    final DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length);
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    UnicastSendingMessageHandler handler = new UnicastSendingMessageHandler("localhost", testPort, true, true,
            "localhost", ackPort, 5000);
    handler.afterPropertiesSet();/*from  w  w  w.  j  av a 2 s  .  co m*/
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            try {
                DatagramSocket socket = new DatagramSocket(testPort);
                latch1.countDown();
                socket.receive(receivedPacket);
                socket.close();
                DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper();
                mapper.setAcknowledge(true);
                mapper.setLengthCheck(true);
                Message<byte[]> message = mapper.toMessage(receivedPacket);
                Object id = message.getHeaders().get(IpHeaders.ACK_ID);
                byte[] ack = id.toString().getBytes();
                DatagramPacket ackPack = new DatagramPacket(ack, ack.length,
                        new InetSocketAddress("localHost", ackPort));
                DatagramSocket out = new DatagramSocket();
                out.send(ackPack);
                out.close();
                latch2.countDown();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    latch1.await(3000, TimeUnit.MILLISECONDS);
    String payload = "foobar";
    handler.handleMessage(MessageBuilder.withPayload(payload).build());
    assertTrue(latch2.await(10000, TimeUnit.MILLISECONDS));
    byte[] src = receivedPacket.getData();
    int length = receivedPacket.getLength();
    int offset = receivedPacket.getOffset();
    byte[] dest = new byte[6];
    System.arraycopy(src, offset + length - 6, dest, 0, 6);
    assertEquals(payload, new String(dest));
    handler.shutDown();
}

From source file:org.graylog2.inputs.transports.UdpTransportTest.java

private void sendUdpDatagram(String hostname, int port, int size) throws IOException {
    final InetAddress address = InetAddress.getByName(hostname);
    final byte[] data = new byte[size];
    final DatagramPacket packet = new DatagramPacket(data, data.length, address, port);

    DatagramSocket toSocket = null;
    try {/*from  w  w  w  .  j av a  2s  .com*/
        toSocket = new DatagramSocket();
        toSocket.send(packet);
    } finally {
        if (toSocket != null) {
            toSocket.close();
        }
    }
}

From source file:werewolf_client.Werewolf_Client.java

public void sentToClient(String adr, int p, String message)
        throws SocketException, UnknownHostException, IOException {
    DatagramSocket sender = new DatagramSocket();
    InetAddress ip = InetAddress.getByName(adr);
    byte[] sendData = new byte[1024];
    sendData = message.getBytes();/*  w ww. jav  a 2s .  c o  m*/

    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ip, p);
    double rand = random.nextDouble();
    if (rand < 0.85) {
        sender.send(sendPacket);
    }
    sender.close();
}