List of usage examples for java.net DatagramSocket close
public void close()
From source file:com.streamsets.pipeline.stage.origin.udp.BaseUDPSourceTest.java
private void doBasicTest(DatagramMode dataFormat, boolean enableEpoll, int numThreads) throws Exception { List<String> ports = NetworkUtils.getRandomPorts(2); final UDPSourceConfigBean conf = new UDPSourceConfigBean(); conf.ports = ports;/*from w ww .j av a2 s . com*/ conf.enableEpoll = enableEpoll; conf.numThreads = 1; conf.dataFormat = dataFormat; conf.maxWaitTime = 1000; conf.batchSize = 1000; conf.collectdCharset = UTF8; conf.syslogCharset = UTF8; conf.rawDataCharset = UTF8; 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 = RAW_SYSLOG_STR.getBytes(UTF8); conf.syslogCharset = UTF8; break; case RAW_DATA: bytes = StringUtils.join(RAW_DATA_VALUES, RAW_DATA_SEPARATOR).getBytes(UTF8); conf.rawDataSeparatorBytes = RAW_DATA_SEPARATOR; conf.rawDataOutputField = RAW_DATA_OUTPUT_FIELD; conf.rawDataCharset = UTF8; conf.rawDataMode = RawDataMode.CHARACTER; break; default: Assert.fail("Unknown data format: " + dataFormat); } initializeRunner(conf, numThreads); 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(); } runProduce(dataFormat, ports); } finally { destroyRunner(); } }
From source file:org.rifidi.emulator.reader.alien.heartbeat.HeartbeatController.java
/** * Send out a heartbeat/*from w ww . ja v a 2s .c om*/ */ 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(); } }
From source file:org.tinymediamanager.core.Utils.java
/** * Sends a wake-on-lan packet for specified MAC address across subnet * /*from w ww .ja v a 2 s. c o m*/ * @param macAddr * the mac address to 'wake up' */ public static final void sendWakeOnLanPacket(String macAddr) { // Broadcast IP address final String IP = "255.255.255.255"; final int port = 7; try { final byte[] MACBYTE = new byte[6]; final String[] hex = macAddr.split("(\\:|\\-)"); for (int i = 0; i < 6; i++) { MACBYTE[i] = (byte) Integer.parseInt(hex[i], 16); } final byte[] bytes = new byte[6 + 16 * MACBYTE.length]; for (int i = 0; i < 6; i++) { bytes[i] = (byte) 0xff; } for (int i = 6; i < bytes.length; i += MACBYTE.length) { System.arraycopy(MACBYTE, 0, bytes, i, MACBYTE.length); } // Send UDP packet here final InetAddress address = InetAddress.getByName(IP); final DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, port); final DatagramSocket socket = new DatagramSocket(); socket.send(packet); socket.close(); LOGGER.info("Sent WOL packet to " + macAddr); } catch (final Exception e) { LOGGER.error("Error sending WOL packet to " + macAddr, e); } }
From source file:org.apache.camel.component.mina.MinaUdpWithInOutUsingPlainSocketTest.java
private String sendAndReceiveUdpMessages(String input) throws Exception { DatagramSocket socket = new DatagramSocket(); InetAddress address = InetAddress.getByName("127.0.0.1"); byte[] data = input.getBytes(); DatagramPacket packet = new DatagramPacket(data, data.length, address, PORT); LOG.debug("+++ Sending data +++"); socket.send(packet);//from w ww.j a v a 2 s.co m Thread.sleep(1000); byte[] buf = new byte[128]; DatagramPacket receive = new DatagramPacket(buf, buf.length, address, PORT); LOG.debug("+++ Receving data +++"); socket.receive(receive); socket.close(); return new String(receive.getData(), 0, receive.getLength()); }
From source file:poisondog.net.udp.SendMission.java
public Void execute(DatagramParameter parameter) throws IOException { DatagramSocket socket = new DatagramSocket(); socket.setReuseAddress(true);//from www .j av a2 s .co 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())); if (parameter.getPort() > 0) packet.setPort(parameter.getPort()); socket.send(packet); socket.close(); return null; }
From source file:IntergrationTest.OCSPIntegrationTest.java
/** * Method to test a port is available.//from w w w . j a v a 2s . c o m * * @param port * * @return */ private boolean available(int port) { if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) { throw new IllegalArgumentException("Invalid start port: " + port); } ServerSocket ss = null; DatagramSocket ds = null; try { ss = new ServerSocket(port); ss.setReuseAddress(true); ds = new DatagramSocket(port); ds.setReuseAddress(true); return true; } catch (IOException e) { } finally { if (ds != null) { ds.close(); } if (ss != null) { try { ss.close(); } catch (IOException e) { /* should not be thrown */ } } } return false; }
From source file:org.apache.camel.component.netty.NettyUdpWithInOutUsingPlainSocketTest.java
private String sendAndReceiveUdpMessages(String input) throws Exception { DatagramSocket socket = new DatagramSocket(); InetAddress address = InetAddress.getByName("127.0.0.1"); // must append delimiter byte[] data = (input + "\n").getBytes(); DatagramPacket packet = new DatagramPacket(data, data.length, address, PORT); LOG.debug("+++ Sending data +++"); socket.send(packet);// ww w. j av a 2 s .c o m Thread.sleep(1000); byte[] buf = new byte[128]; DatagramPacket receive = new DatagramPacket(buf, buf.length, address, PORT); LOG.debug("+++ Receiving data +++"); socket.receive(receive); socket.close(); return new String(receive.getData(), 0, receive.getLength()); }
From source file:org.loggo.server.SimpleServerIT.java
@Test(timeout = 60 * 1000) public void sunnyDay() throws Exception { // no log files exist assertEquals(0, Iterators.size(conn.createScanner("logs", Authorizations.EMPTY).iterator())); // send a tcp message Socket s = new Socket("localhost", loggerPort); assertTrue(s.isConnected());/*from w w w .j a v a2 s. c om*/ s.getOutputStream() .write("localhost tester 2014-01-01 01:01:01,123 This is a test message\n\n".getBytes(UTF_8)); s.close(); // send a udp message DatagramSocket ds = new DatagramSocket(); String otherMessage = "localhost test2 2014-01-01 01:01:01,345 [INFO] This is a 2nd message"; byte[] otherMessageBytes = otherMessage.getBytes(UTF_8); InetSocketAddress dest = new InetSocketAddress("localhost", loggerPort); ds.send(new DatagramPacket(otherMessageBytes, otherMessageBytes.length, dest)); ds.close(); // wait for a flush sleepUninterruptibly(8, TimeUnit.SECONDS); // verify the messages are stored Scanner scanner = conn.createScanner("logs", Authorizations.EMPTY); assertEquals(2, Iterators.size(scanner.iterator())); Iterator<Entry<Key, Value>> iter = scanner.iterator(); Entry<Key, Value> next = iter.next(); assertEquals(next.getValue().toString(), "This is a test message"); assertEquals(next.getKey().getColumnQualifier().toString(), "tester\0localhost"); assertEquals(next.getKey().getColumnFamily().toString(), "UNKNOWN"); assertTrue(next.getKey().getRow().toString().endsWith("2014-01-01 01:01:01,123")); next = iter.next(); assertEquals(next.getValue().toString(), "[INFO] This is a 2nd message"); assertEquals(next.getKey().getColumnQualifier().toString(), "test2\0localhost"); assertTrue(next.getKey().getRow().toString().endsWith("2014-01-01 01:01:01,123")); assertFalse(iter.hasNext()); sleepUninterruptibly(30, TimeUnit.SECONDS); conn.tableOperations().deleteRows("logs", null, null); }
From source file:org.apache.axis2.transport.udp.UDPSender.java
@Override public void sendMessage(MessageContext msgContext, String targetEPR, OutTransportInfo outTransportInfo) throws AxisFault { UDPOutTransportInfo udpOutInfo;//w w w .j a v a2 s .c o m if ((targetEPR == null) && (outTransportInfo != null)) { // this can happen only at the server side and send the message using back chanel udpOutInfo = (UDPOutTransportInfo) outTransportInfo; } else { udpOutInfo = new UDPOutTransportInfo(targetEPR); } MessageFormatter messageFormatter = TransportUtils.getMessageFormatter(msgContext); OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext); format.setContentType(udpOutInfo.getContentType()); byte[] payload = messageFormatter.getBytes(msgContext, format); try { DatagramSocket socket = new DatagramSocket(); if (log.isDebugEnabled()) { log.debug("Sending " + payload.length + " bytes to " + udpOutInfo.getAddress()); } try { socket.send(new DatagramPacket(payload, payload.length, udpOutInfo.getAddress())); if (!msgContext.getOptions().isUseSeparateListener() && !msgContext.isServerSide()) { waitForReply(msgContext, socket, udpOutInfo.getContentType()); } } finally { socket.close(); } } catch (IOException ex) { throw new AxisFault("Unable to send packet", ex); } }
From source file:io.github.gsteckman.rpi_rest.SsdpHandler.java
private void sendResponse(final SocketAddress addr) { if (!(addr instanceof InetSocketAddress)) { LOG.warn("Don't know how to handle non Internet addresses"); return;// ww w . ja va 2s. c om } DatagramSocket sock = null; LOG.debug("Responding to " + addr.toString()); try { sock = new DatagramSocket(); sock.connect(addr); byte[] ba = generateSearchResponse().getBytes(); sock.send(new DatagramPacket(ba, ba.length)); } catch (IOException e) { LOG.error(e.getMessage()); } finally { if (sock != null) { sock.close(); } } }