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.navercorp.pinpoint.collector.receiver.thrift.udp.UDPReceiverTest.java

@Test
public void socketBufferSize() throws SocketException {
    DatagramSocket datagramSocket = new DatagramSocket();
    int receiveBufferSize = datagramSocket.getReceiveBufferSize();
    logger.debug("{}", receiveBufferSize);

    datagramSocket.setReceiveBufferSize(64 * 1024 * 10);
    logger.debug("{}", datagramSocket.getReceiveBufferSize());

    datagramSocket.close();
}

From source file:org.wso2.esb.integration.common.utils.clients.UDPClient.java

/**
 * Send UDP message//from   w ww. ja  v  a2 s . c  o m
 *
 * @param message message
 */
public void sendMessage(String message) throws IOException {
    DatagramSocket clientSocket = null;

    try {
        clientSocket = new DatagramSocket();
        InetAddress inetAddress = InetAddress.getByName(host);
        byte[] sendData = message.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, inetAddress, port);
        clientSocket.send(sendPacket);
    } finally {
        if (clientSocket != null) {
            clientSocket.close();
        }
    }
}

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

@Test
public void verifySendMulticastWithAcks() throws Exception {

    MulticastSocket socket;// ww w . j  a  va 2 s  . c om
    try {
        socket = new MulticastSocket();
    } catch (Exception e) {
        return;
    }
    final int testPort = socket.getLocalPort();
    final AtomicInteger ackPort = new AtomicInteger();

    final String multicastAddress = "225.6.7.8";
    final String payload = "foobar";
    final CountDownLatch listening = new CountDownLatch(2);
    final CountDownLatch ackListening = new CountDownLatch(1);
    final CountDownLatch ackSent = new CountDownLatch(2);
    Runnable catcher = () -> {
        try {
            byte[] buffer = new byte[1000];
            DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length);
            MulticastSocket socket1 = new MulticastSocket(testPort);
            socket1.setInterface(InetAddress.getByName(multicastRule.getNic()));
            socket1.setSoTimeout(8000);
            InetAddress group = InetAddress.getByName(multicastAddress);
            socket1.joinGroup(group);
            listening.countDown();
            assertTrue(ackListening.await(10, TimeUnit.SECONDS));
            LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " waiting for packet");
            socket1.receive(receivedPacket);
            socket1.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(multicastRule.getNic(), ackPort.get()));
            DatagramSocket out = new DatagramSocket();
            out.send(ackPack);
            LogFactory.getLog(getClass())
                    .debug(Thread.currentThread().getName() + " sent ack to " + ackPack.getSocketAddress());
            out.close();
            ackSent.countDown();
            socket1.close();
        } catch (Exception e) {
            listening.countDown();
            e.printStackTrace();
        }
    };
    Executor executor = Executors.newFixedThreadPool(2);
    executor.execute(catcher);
    executor.execute(catcher);
    assertTrue(listening.await(10000, TimeUnit.MILLISECONDS));
    MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(multicastAddress, testPort,
            true, true, "localhost", 0, 10000);
    handler.setLocalAddress(this.multicastRule.getNic());
    handler.setMinAcksForSuccess(2);
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.afterPropertiesSet();
    handler.start();
    waitAckListening(handler);
    ackPort.set(handler.getAckPort());
    ackListening.countDown();
    handler.handleMessage(MessageBuilder.withPayload(payload).build());
    assertTrue(ackSent.await(10000, TimeUnit.MILLISECONDS));
    handler.stop();
    socket.close();
}

From source file:com.all.landownloader.discovery.LanDiscoverySocket.java

public void reply(InetAddress address) throws IllegalArgumentException {
    try {//from w  w w  . j  a v  a  2  s.  c o  m
        byte[] buf = createPacket(REPLY_MSG);
        DatagramPacket packet = new DatagramPacket(buf, buf.length, address, PORT);
        DatagramSocket socket = new DatagramSocket();
        socket.send(packet);
        socket.close();
    } catch (IOException e) {
    }
}

From source file:com.mendhak.gpslogger.common.OpenGTSClient.java

public void sendRAW(String id, String accountName, SerializableLocation[] locations) throws Exception {
    for (SerializableLocation loc : locations) {
        if (Utilities.IsNullOrEmpty(accountName)) {
            accountName = id;/*from  w  w w . ja va 2s .  c  o m*/
        }
        String message = accountName + "/" + id + "/" + GPRMCEncode(loc);
        DatagramSocket socket = new DatagramSocket();
        byte[] buffer = message.getBytes();
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getByName(server), port);
        tracer.debug("Sending UDP " + message);
        socket.send(packet);
        socket.close();
    }
}

From source file:org.mule.test.firewall.FirewallTestCase.java

protected void doTestUdp(InetAddress address, int port) throws Exception {
    try {/*from  w ww.ja v  a 2s.  c  om*/
        logger.debug("Testing UDP on " + addressToString(address, port));
        DatagramSocket server = openUdpServer(address, port);
        DatagramSocket client = openUdpClient();
        client.send(new DatagramPacket(new byte[] { 1 }, 1, address, port));
        DatagramPacket packet = new DatagramPacket(new byte[1], 1);
        server.receive(packet);
        assertEquals("Failed to send packet via " + addressToString(address, port), 1, packet.getData()[0]);
        client.close();
        server.close();
    } catch (Exception e) {
        logger.error("Error while attempting UDP message on " + addressToString(address, port));
        throw e;
    }
}

From source file:com.streamsets.pipeline.stage.origin.udp.TestUDPSource.java

private void doBasicTest(UDPDataFormat dataFormat) throws Exception {
    List<String> ports = NetworkUtils.getRandomPorts(2);
    ParserConfig parserConfig = new ParserConfig();
    parserConfig.put(CHARSET, "UTF-8");
    TUDPSource source = new TUDPSource(ports, parserConfig, dataFormat, 20, 100L);
    SourceRunner runner = new SourceRunner.Builder(TUDPSource.class, source).addOutputLane("lane").build();
    runner.runInit();// w  w  w  .  j  av a2  s.  c  om
    try {
        byte[] bytes = null;
        switch (dataFormat) {
        case NETFLOW:
            InputStream is = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream(TEN_PACKETS_RESOURCE);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IOUtils.copy(is, baos);
            is.close();
            baos.close();
            bytes = baos.toByteArray();
            break;
        case SYSLOG:
            bytes = "<34>1 2003-10-11T22:14:15.003Z mymachine.example.com some syslog data"
                    .getBytes(StandardCharsets.UTF_8);
            break;
        default:
            Assert.fail("Unknown data format: " + dataFormat);
        }
        for (String port : ports) {
            DatagramSocket clientSocket = new DatagramSocket();
            InetAddress address = InetAddress.getLoopbackAddress();
            DatagramPacket sendPacket = new DatagramPacket(bytes, bytes.length, address,
                    Integer.parseInt(port));
            clientSocket.send(sendPacket);
            clientSocket.close();
        }
        StageRunner.Output output = runner.runProduce(null, 6);
        Assert.assertTrue(source.produceCalled);
        List<Record> records = output.getRecords().get("lane");
        switch (dataFormat) {
        case NETFLOW:
            Assert.assertEquals(String.valueOf(records), 6, records.size());
            break;
        case SYSLOG:
            Assert.assertEquals(String.valueOf(records), ports.size(), records.size());
            break;
        default:
            Assert.fail("Unknown data format: " + dataFormat);
        }
        output = runner.runProduce(null, 14);
        Assert.assertTrue(source.produceCalled);
        records = output.getRecords().get("lane");
        switch (dataFormat) {
        case NETFLOW:
            Assert.assertEquals(String.valueOf(records), 14, records.size());
            break;
        case SYSLOG:
            Assert.assertEquals(String.valueOf(records), 0, records.size());
            break;
        default:
            Assert.fail("Unknown data format: " + dataFormat);
        }
        output = runner.runProduce(null, 1);
        Assert.assertTrue(source.produceCalled);
        records = output.getRecords().get("lane");
        Assert.assertEquals(String.valueOf(records), 0, records.size());
    } finally {
        runner.runDestroy();
    }
}

From source file:com.clustercontrol.poller.impl.UdpTransportMappingImpl.java

/**
 * Closes the socket and stops the listener thread.
 *
 * @throws IOException//from w  w w  .  j a va 2  s  .co m
 */
public void close() throws IOException {
    boolean interrupted = false;
    WorkerTask l = listener;
    if (l != null) {
        l.terminate();
        l.interrupt();
        if (socketTimeout > 0) {
            try {
                l.join();
            } catch (InterruptedException ex) {
                interrupted = true;
                logger.warn(ex);
            }
        }
        listener = null;
    }
    DatagramSocket closingSocket = socket;
    if ((closingSocket != null) && (!closingSocket.isClosed())) {
        closingSocket.close();
    }
    socket = null;
    if (interrupted) {
        Thread.currentThread().interrupt();
    }
}

From source file:com.clustercontrol.poller.impl.UdpTransportMappingImpl.java

/**
 * If receiving new datagrams fails with a {@link SocketException}, this
 * method is called to renew the socket - if possible.
 * //from www .  j a v  a  2  s. c om
 * @param socketException
 *            the exception that occurred.
 * @param failedSocket
 *            the socket that caused the exception. By default, he socket
 *            will be closed in order to be able to reopen it.
 *            Implementations may also try to reuse the socket, in
 *            dependence of the <code>socketException</code>.
 * @return the new socket or <code>null</code> if the listen thread should
 *         be terminated with the provided exception.
 * @throws SocketException
 *             a new socket exception if the socket could not be renewed.
 * @since 2.2.2
 */
protected DatagramSocket renewSocketAfterException(SocketException socketException, DatagramSocket failedSocket)
        throws SocketException {
    if ((failedSocket != null) && (!failedSocket.isClosed())) {
        failedSocket.close();
    }
    DatagramSocket s = new DatagramSocket(udpAddress.getPort(), udpAddress.getInetAddress());
    s.setSoTimeout(socketTimeout);
    return s;
}

From source file:org.openhab.binding.modbus.internal.TestCaseSupport.java

private void startUDPServer() throws UnknownHostException, InterruptedException {
    udpListener = new ModbusUDPListener(localAddress(), udpTerminalFactory);
    for (int portCandidate = 10000 + udpServerIndex.increment(); portCandidate < 20000; portCandidate++) {
        try {//from   w w w .  j  a v  a2 s  .c  om
            DatagramSocket socket = new DatagramSocket(portCandidate);
            socket.close();
            udpListener.setPort(portCandidate);
            break;
        } catch (SocketException e) {
            continue;
        }
    }

    udpListener.start();
    waitForUDPServerStartup();
    Assert.assertNotSame(-1, udpModbusPort);
    Assert.assertNotSame(0, udpModbusPort);
}