Here are the examples of the java api class java.net.DatagramSocket taken from open source projects.
1. UDPTransportHandlerTest#testSendData()
Project: TLS-Attacker
File: UDPTransportHandlerTest.java
File: UDPTransportHandlerTest.java
@Test public void testSendData() throws Exception { UDPTransportHandler udpTH = new UDPTransportHandler(); DatagramSocket testSocket = new DatagramSocket(); testSocket.setSoTimeout(1000); udpTH.initialize(localhost.getHostName(), testSocket.getLocalPort()); byte[] txData = new byte[8192]; RandomHelper.getRandom().nextBytes(txData); byte[] rxData = new byte[8192]; DatagramPacket rxPacket = new DatagramPacket(rxData, rxData.length, localhost, testSocket.getLocalPort()); udpTH.sendData(txData); testSocket.receive(rxPacket); assertEquals("Confirm size of the sent data", txData.length, rxPacket.getLength()); assertArrayEquals("Confirm sent data equals received data", txData, rxPacket.getData()); udpTH.closeConnection(); testSocket.close(); }
2. UdpSocketTest#createUdpSocket()
Project: pinpoint
File: UdpSocketTest.java
File: UdpSocketTest.java
// @Test public void createUdpSocket() throws IOException { DatagramSocket so = new DatagramSocket(); // so.bind(new InetSocketAddress("localhost", 8081)); // DatagramSocket receiver = new DatagramSocket(new InetSocketAddress("localhost", 8082)); // receiver.bind(new InetSocketAddress("localhost", 8082)); so.connect(new InetSocketAddress("localhost", 8082)); so.send(new DatagramPacket(new byte[10], 10)); // receiver.receive(newDatagramPacket(1000)); so.close(); }
3. NettyUdpWithInOutUsingPlainSocketTest#sendAndReceiveUdpMessages()
Project: camel
File: NettyUdpWithInOutUsingPlainSocketTest.java
File: 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, getPort()); LOG.debug("+++ Sending data +++"); socket.send(packet); Thread.sleep(1000); byte[] buf = new byte[128]; DatagramPacket receive = new DatagramPacket(buf, buf.length, address, getPort()); LOG.debug("+++ Receiving data +++"); socket.receive(receive); socket.close(); return new String(receive.getData(), 0, receive.getLength()); }
4. NettyUdpWithInOutUsingPlainSocketTest#sendAndReceiveUdpMessages()
Project: camel
File: NettyUdpWithInOutUsingPlainSocketTest.java
File: 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, getPort()); LOG.debug("+++ Sending data +++"); socket.send(packet); Thread.sleep(1000); byte[] buf = new byte[128]; DatagramPacket receive = new DatagramPacket(buf, buf.length, address, getPort()); LOG.debug("+++ Receiving data +++"); socket.receive(receive); socket.close(); return new String(receive.getData(), 0, receive.getLength()); }
5. Mina2UdpWithInOutUsingPlainSocketTest#sendAndReceiveUdpMessages()
Project: camel
File: Mina2UdpWithInOutUsingPlainSocketTest.java
File: Mina2UdpWithInOutUsingPlainSocketTest.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, getPort()); LOG.debug("+++ Sending data +++"); socket.send(packet); Thread.sleep(1000); byte[] buf = new byte[128]; DatagramPacket receive = new DatagramPacket(buf, buf.length, address, getPort()); LOG.debug("+++ Receiveing data +++"); socket.receive(receive); socket.close(); return new String(receive.getData(), 0, receive.getLength()); }
6. MinaUdpWithInOutUsingPlainSocketTest#sendAndReceiveUdpMessages()
Project: camel
File: MinaUdpWithInOutUsingPlainSocketTest.java
File: 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, getPort()); LOG.debug("+++ Sending data +++"); socket.send(packet); Thread.sleep(1000); byte[] buf = new byte[128]; DatagramPacket receive = new DatagramPacket(buf, buf.length, address, getPort()); LOG.debug("+++ Receiveing data +++"); socket.receive(receive); socket.close(); return new String(receive.getData(), 0, receive.getLength()); }
7. Service#send()
Project: bnd
File: Service.java
File: Service.java
private String send(int port, String m) throws Exception { if (port == -1) return "Invalid port"; byte data[] = m.getBytes("UTF-8"); DatagramPacket p = new DatagramPacket(data, 0, data.length, InetAddress.getLoopbackAddress(), port); DatagramSocket dsocket = new DatagramSocket(); dsocket.setReceiveBufferSize(5000); dsocket.setSoTimeout(5000); try { dsocket.send(p); byte[] buffer = new byte[BUFFER_SIZE]; DatagramPacket dp = new DatagramPacket(buffer, BUFFER_SIZE); dsocket.receive(dp); return new String(dp.getData(), dp.getOffset(), dp.getLength(), "UTF-8"); } catch (SocketTimeoutException stoe) { return "Timed out"; } finally { dsocket.close(); } }
8. NettyUdpReceiverTest#start()
Project: pinpoint
File: NettyUdpReceiverTest.java
File: NettyUdpReceiverTest.java
private void start() throws IOException, InterruptedException { DatagramSocket so = new DatagramSocket(); so.connect(new InetSocketAddress("127.0.0.1", PORT)); int count = 1000; for (int i = 0; i < count; i++) { byte[] bytes = new byte[100]; DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length); so.send(datagramPacket); Thread.sleep(10); } so.close(); }
9. Network#getIp()
Project: happy-dns-java
File: Network.java
File: Network.java
// use udp socket connect, tcp socket would connect when new. public static String getIp() { DatagramSocket socket = null; try { socket = new DatagramSocket(); InetAddress addr = InetAddress.getByName("114.114.114.114"); socket.connect(addr, 53); } catch (IOException e) { e.printStackTrace(); return ""; } InetAddress local = socket.getLocalAddress(); socket.close(); return local.getHostAddress(); }
10. DTLSClientTest#openDTLSConnection()
Project: bc-java
File: DTLSClientTest.java
File: DTLSClientTest.java
private static DTLSTransport openDTLSConnection(InetAddress address, int port, TlsClient client) throws IOException { DatagramSocket socket = new DatagramSocket(); socket.connect(address, port); int mtu = 1500; DatagramTransport transport = new UDPTransport(socket, mtu); transport = new UnreliableDatagramTransport(transport, secureRandom, 0, 0); transport = new LoggingDatagramTransport(transport, System.out); DTLSClientProtocol protocol = new DTLSClientProtocol(secureRandom); return protocol.connect(client, transport); }
11. DatagramTimeout#main()
Project: openjdk
File: DatagramTimeout.java
File: DatagramTimeout.java
public static void main(String[] args) throws Exception { boolean success = false; DatagramSocket sock = new DatagramSocket(); try { DatagramPacket p; byte[] buffer = new byte[50]; p = new DatagramPacket(buffer, buffer.length); sock.setSoTimeout(2); sock.receive(p); } catch (SocketTimeoutException e) { success = true; } finally { sock.close(); } if (!success) throw new RuntimeException("Socket timeout failure."); }
12. DatagramLoggingActivityFactoryTest#testActivityReceipt()
Project: oodt
File: DatagramLoggingActivityFactoryTest.java
File: DatagramLoggingActivityFactoryTest.java
/** * Test construction and transmission of datagrams. * * @throws SocketException if an error occurs. * @throws IOException if an error occurs. * @throws ClassNotFoundException if an error occurs. */ public void testActivityReceipt() throws IOException, ClassNotFoundException { DatagramSocket socket = null; try { byte[] buf = new byte[512]; DatagramPacket packet = new DatagramPacket(buf, buf.length); socket = new DatagramSocket(); System.setProperty("activity.host", "localhost"); System.setProperty("activity.port", String.valueOf(socket.getLocalPort())); DatagramLoggingActivityFactory fac = new DatagramLoggingActivityFactory(); Activity a = fac.createActivity(); Incident i = new Incident(); a.log(i); socket.receive(packet); ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(packet.getData(), packet.getOffset(), packet.getLength())); Incident j = (Incident) ois.readObject(); assertEquals(i, j); } finally { if (socket != null) socket.close(); } }
13. DatagramLogger#main()
Project: oodt
File: DatagramLogger.java
File: DatagramLogger.java
public static void main(String[] argv) throws Throwable { if (argv.length > 0) { System.err.println("This program takes NO command line arguments."); System.err.println("Set the activity.port property to adjust the port number."); System.err.println("Set the activity.storage property to set the Storage class to use."); System.exit(1); } int port = Integer.getInteger("activity.port", VAL); String className = System.getProperty("activity.storage"); if (className == null) { System.err.println("No Storage class defined via the `activity.storage' property; exiting..."); System.exit(1); } Class storageClass = Class.forName(className); storage = (Storage) storageClass.newInstance(); DatagramSocket socket = new DatagramSocket(port); byte[] buf = new byte[INT]; DatagramPacket packet = new DatagramPacket(buf, buf.length); for (; ; ) { socket.receive(packet); byte[] received = new byte[packet.getLength()]; System.arraycopy(packet.getData(), packet.getOffset(), received, 0, packet.getLength()); new ReceiverThread(received).start(); } }
14. UdpPingController#startReceiving()
Project: ninja
File: UdpPingController.java
File: UdpPingController.java
@Start(order = 90) public void startReceiving() throws IOException { log.info("Starting UDP listener on port 19876"); serverSocket = new DatagramSocket(19876); receiveThread = new Thread(new Runnable() { @Override public void run() { byte[] receiveData = new byte[1024]; try { while (true) { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); log.info("Received UDP packet from " + receivePacket.getAddress() + ": " + new String(receivePacket.getData(), 0, receivePacket.getLength())); count.incrementAndGet(); } } catch (IOException e) { } } }); receiveThread.start(); }
15. TestUtils#isUdpPortAvailable()
Project: netty
File: TestUtils.java
File: TestUtils.java
private static boolean isUdpPortAvailable(InetSocketAddress localAddress) { DatagramSocket ds = null; try { ds = new DatagramSocket(null); ds.setReuseAddress(false); ds.bind(localAddress); ds.close(); ds = null; return true; } catch (Exception ignore) { } finally { if (ds != null) { ds.close(); } } return false; }
16. AvailablePortFinder#available()
Project: logging-log4j2
File: AvailablePortFinder.java
File: AvailablePortFinder.java
/** * Checks to see if a specific port is available. * * @param port the port number to check for availability * @return {@code true} if the port is available, or {@code false} if not * @throws IllegalArgumentException is thrown if the port number is out of range */ public static synchronized boolean available(final int port) throws IllegalArgumentException { if (port < currentMinPort.get() || port > MAX_PORT_NUMBER) { throw new IllegalArgumentException("Invalid start currentMinPort: " + 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 (final IOException e) { } finally { Closer.closeSilently(ds); Closer.closeSilently(ss); } return false; }
17. Client#discoverHost()
Project: kryonet
File: Client.java
File: Client.java
/** Broadcasts a UDP message on the LAN to discover any running servers. The address of the first server to respond is returned. * @param udpPort The UDP port of the server. * @param timeoutMillis The number of milliseconds to wait for a response. * @return the first server found, or null if no server responded. */ public InetAddress discoverHost(int udpPort, int timeoutMillis) { DatagramSocket socket = null; try { socket = new DatagramSocket(); broadcast(udpPort, socket); socket.setSoTimeout(timeoutMillis); DatagramPacket packet = discoveryHandler.onRequestNewDatagramPacket(); try { socket.receive(packet); } catch (SocketTimeoutException ex) { if (INFO) info("kryonet", "Host discovery timed out."); return null; } if (INFO) info("kryonet", "Discovered server: " + packet.getAddress()); discoveryHandler.onDiscoveredHost(packet, getKryo()); return packet.getAddress(); } catch (IOException ex) { if (ERROR) error("kryonet", "Host discovery failed.", ex); return null; } finally { if (socket != null) socket.close(); discoveryHandler.onFinally(); } }
18. Packet#send()
Project: Kore
File: Packet.java
File: Packet.java
/** * Sends this packet to the EventServer * @param adr Address of the EventServer * @param port Port of the EventServer * @throws IOException */ public void send(InetAddress adr, int port) throws IOException { int maxseq = getNumPackets(); DatagramSocket s = new DatagramSocket(); // For each Packet in Sequence... for (int seq = 1; seq <= maxseq; seq++) { // Get Message and send them... byte[] pack = getUDPMessage(seq); DatagramPacket p = new DatagramPacket(pack, pack.length); p.setAddress(adr); p.setPort(port); s.send(p); } }
19. CellarTestSupport#isPortAvailable()
Project: karaf-cellar
File: CellarTestSupport.java
File: CellarTestSupport.java
/** * Returns true if port is available for use. * * @param port * @return */ public static boolean isPortAvailable(int 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) { } } } return false; }
20. DatagramSocketFactoryTest#testDatagramSocketFactoryMakeObject()
Project: jmxtrans
File: DatagramSocketFactoryTest.java
File: DatagramSocketFactoryTest.java
@Test public void testDatagramSocketFactoryMakeObject() throws Exception { DatagramSocketFactory socketFactory = new DatagramSocketFactory(); InetSocketAddress socketAddress = new InetSocketAddress(Inet4Address.getLocalHost(), PORT); DatagramSocket socketObject = socketFactory.makeObject(socketAddress); // Test if the remote address/port is the correct one. assertThat(socketObject.getPort()).isEqualTo(PORT); assertThat(socketObject.getInetAddress()).isEqualTo(Inet4Address.getLocalHost()); }
21. DatagramTimeout#main()
Project: jdk7u-jdk
File: DatagramTimeout.java
File: DatagramTimeout.java
public static void main(String[] args) throws Exception { boolean success = false; DatagramSocket sock = new DatagramSocket(); try { DatagramPacket p; byte[] buffer = new byte[50]; p = new DatagramPacket(buffer, buffer.length); sock.setSoTimeout(2); sock.receive(p); } catch (SocketTimeoutException e) { success = true; } finally { sock.close(); } if (!success) throw new RuntimeException("Socket timeout failure."); }
22. DatagramChannelTest#test_read_intoReadOnlyByteArrays()
Project: j2objc
File: DatagramChannelTest.java
File: DatagramChannelTest.java
public void test_read_intoReadOnlyByteArrays() throws Exception { ByteBuffer readOnly = ByteBuffer.allocate(1).asReadOnlyBuffer(); DatagramSocket ds = new DatagramSocket(0); DatagramChannel dc = DatagramChannel.open(); dc.connect(ds.getLocalSocketAddress()); try { dc.read(readOnly); fail(); } catch (IllegalArgumentException expected) { } try { dc.read(new ByteBuffer[] { readOnly }); fail(); } catch (IllegalArgumentException expected) { } try { dc.read(new ByteBuffer[] { readOnly }, 0, 1); fail(); } catch (IllegalArgumentException expected) { } }
23. DatagramSocketTest#testInitialState()
Project: j2objc
File: DatagramSocketTest.java
File: DatagramSocketTest.java
public void testInitialState() throws Exception { DatagramSocket ds = new DatagramSocket(); try { assertTrue(ds.isBound()); // The RI starts DatagramSocket in broadcast mode. assertTrue(ds.getBroadcast()); assertFalse(ds.isClosed()); assertFalse(ds.isConnected()); assertTrue(ds.getLocalPort() > 0); assertTrue(ds.getLocalAddress().isAnyLocalAddress()); InetSocketAddress socketAddress = (InetSocketAddress) ds.getLocalSocketAddress(); assertEquals(ds.getLocalPort(), socketAddress.getPort()); assertEquals(ds.getLocalAddress(), socketAddress.getAddress()); assertNull(ds.getInetAddress()); assertEquals(-1, ds.getPort()); assertNull(ds.getRemoteSocketAddress()); assertFalse(ds.getReuseAddress()); assertNull(ds.getChannel()); } finally { ds.close(); } }
24. HeroicStartupPinger#sendUDP()
Project: heroic
File: HeroicStartupPinger.java
File: HeroicStartupPinger.java
private void sendUDP(PingMessage p) throws IOException { if (ping.getPort() == -1) { throw new IllegalArgumentException("Invalid URI, port is required: " + ping); } final byte[] frame = mapper.writeValueAsBytes(p); InetSocketAddress address = new InetSocketAddress(ping.getHost(), ping.getPort()); final DatagramPacket packet = new DatagramPacket(frame, frame.length, address); try (final DatagramSocket socket = new DatagramSocket()) { socket.send(packet); } }
25. Resolver#udpCommunicate()
Project: happy-dns-java
File: Resolver.java
File: Resolver.java
private byte[] udpCommunicate(byte[] question) throws IOException { DatagramSocket socket = null; try { socket = new DatagramSocket(); DatagramPacket packet = new DatagramPacket(question, question.length, address, 53); socket.setSoTimeout(10000); socket.send(packet); packet = new DatagramPacket(new byte[1500], 1500); socket.receive(packet); return packet.getData(); } finally { if (socket != null) { socket.close(); } } }
26. UdpTransportTest#sendUdpDatagram()
Project: graylog2-server
File: UdpTransportTest.java
File: 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 { toSocket = new DatagramSocket(); toSocket.send(packet); } finally { if (toSocket != null) { toSocket.close(); } } }
27. UdpHelper#send()
Project: freedomotic
File: UdpHelper.java
File: UdpHelper.java
/** * Sends an UDP packet to the server * * @param serverAddress UDP server address * @param serverPort UDP server port number * @param payload data to send * @throws java.io.IOException */ public void send(String serverAddress, int serverPort, String payload) throws IOException { DatagramSocket datagramSocket = null; try { InetAddress inetAddress = InetAddress.getByName(serverAddress); int port = serverPort; datagramSocket = new DatagramSocket(); DatagramPacket out_datagramPacket = new DatagramPacket(payload.getBytes(), payload.length(), inetAddress, port); datagramSocket.send(out_datagramPacket); LOG.debug("Sending UDP packet to {}:{}", new Object[] { serverAddress, serverPort }); } catch (UnknownHostException ex) { throw new IOException("Unknown UDP server. Packet not sent", ex); } catch (SocketException ex) { throw new IOException("Socket exception. Packet not sent", ex); } finally { if (datagramSocket != null) { datagramSocket.close(); } } }
28. UdpConnection#openSocket()
Project: etch
File: UdpConnection.java
File: UdpConnection.java
@Override protected synchronized boolean openSocket(boolean reconnect) throws Exception { if (socket != null) socket.close(); socket = new DatagramSocket(); if (listen) socket.bind(host != null ? new InetSocketAddress(host, port) : new InetSocketAddress(port)); else socket.connect(new InetSocketAddress(host, port)); if (!reconnect && socket != null) return true; return false; }
29. RandomPortFinder#available()
Project: datacollector
File: RandomPortFinder.java
File: RandomPortFinder.java
private static boolean available(final int port) { ServerSocket serverSocket = null; DatagramSocket dataSocket = null; try { serverSocket = new ServerSocket(port); serverSocket.setReuseAddress(true); dataSocket = new DatagramSocket(port); dataSocket.setReuseAddress(true); return true; } catch (final IOException e) { return false; } finally { if (dataSocket != null) { dataSocket.close(); } if (serverSocket != null) { try { serverSocket.close(); } catch (final IOException e) { } } } }
30. SSDPSearchResponseSocket#start()
Project: cybergarage-upnp
File: SSDPSearchResponseSocket.java
File: SSDPSearchResponseSocket.java
public void start() { StringBuffer name = new StringBuffer("Cyber.SSDPSearchResponseSocket/"); DatagramSocket s = getDatagramSocket(); // localAddr is null on Android m3-rc37a (01/30/08) InetAddress localAddr = s.getLocalAddress(); if (localAddr != null) { name.append(s.getLocalAddress()).append(':'); name.append(s.getLocalPort()); } deviceSearchResponseThread = new Thread(this, name.toString()); deviceSearchResponseThread.start(); }
31. NettyManyUDPMessagesTest#testSendingManyMessages()
Project: camel
File: NettyManyUDPMessagesTest.java
File: NettyManyUDPMessagesTest.java
@Test public void testSendingManyMessages() throws Exception, InterruptedException { MockEndpoint stop1 = getMockEndpoint("mock:stop1"); MockEndpoint stop2 = getMockEndpoint("mock:stop2"); stop2.expectedMessageCount(messageCount); stop1.expectedMessageCount(messageCount); DatagramSocket socket = new DatagramSocket(); try { InetAddress address = InetAddress.getByName("127.0.0.1"); for (int i = 0; i < messageCount; i++) { byte[] data = message.getBytes(); DatagramPacket packet = new DatagramPacket(data, data.length, address, serverPort); socket.send(packet); Thread.sleep(100); } } finally { socket.close(); } assertMockEndpointsSatisfied(); }
32. MinaManyUDPMessagesTest#testSendingManyMessages()
Project: camel
File: MinaManyUDPMessagesTest.java
File: MinaManyUDPMessagesTest.java
@Test public void testSendingManyMessages() throws Exception, InterruptedException { MockEndpoint stop1 = getMockEndpoint("mock:stop1"); MockEndpoint stop2 = getMockEndpoint("mock:stop2"); stop2.expectedMessageCount(messageCount); stop1.expectedMessageCount(messageCount); DatagramSocket socket = new DatagramSocket(); try { InetAddress address = InetAddress.getByName("127.0.0.1"); for (int i = 0; i < messageCount; i++) { byte[] data = message.getBytes(); DatagramPacket packet = new DatagramPacket(data, data.length, address, serverPort); socket.send(packet); Thread.sleep(100); } } finally { socket.close(); } assertMockEndpointsSatisfied(); }
33. Mina2UdpTest#sendUdpMessages()
Project: camel
File: Mina2UdpTest.java
File: Mina2UdpTest.java
protected void sendUdpMessages() throws Exception { DatagramSocket socket = new DatagramSocket(); try { InetAddress address = InetAddress.getByName("127.0.0.1"); for (int i = 0; i < messageCount; i++) { String text = "Hello Message: " + Integer.toString(i); byte[] data = text.getBytes(); DatagramPacket packet = new DatagramPacket(data, data.length, address, getPort()); socket.send(packet); } Thread.sleep(2000); } finally { socket.close(); } }
34. Mina2UdpConcurrentTest#sendUdpMessages()
Project: camel
File: Mina2UdpConcurrentTest.java
File: Mina2UdpConcurrentTest.java
protected void sendUdpMessages() throws Exception { DatagramSocket socket = new DatagramSocket(); try { InetAddress address = InetAddress.getByName("127.0.0.1"); for (int i = 0; i < messageCount; i++) { String text = "Hello Message: " + Integer.toString(i); byte[] data = text.getBytes(); DatagramPacket packet = new DatagramPacket(data, data.length, address, getPort()); socket.send(packet); } Thread.sleep(2000); } finally { socket.close(); } }
35. Mina2SslContextParametersUdpTest#sendUdpMessages()
Project: camel
File: Mina2SslContextParametersUdpTest.java
File: Mina2SslContextParametersUdpTest.java
protected void sendUdpMessages() throws Exception { DatagramSocket socket = new DatagramSocket(); try { InetAddress address = InetAddress.getByName("127.0.0.1"); for (int i = 0; i < messageCount; i++) { String text = "Hello Message: " + Integer.toString(i); byte[] data = text.getBytes(); DatagramPacket packet = new DatagramPacket(data, data.length, address, getPort()); socket.send(packet); } Thread.sleep(2000); } finally { socket.close(); } }
36. MinaUdpTest#sendUdpMessages()
Project: camel
File: MinaUdpTest.java
File: MinaUdpTest.java
protected void sendUdpMessages() throws Exception { DatagramSocket socket = new DatagramSocket(); try { InetAddress address = InetAddress.getByName("127.0.0.1"); for (int i = 0; i < messageCount; i++) { String text = "Hello Message: " + i; byte[] data = text.getBytes(); DatagramPacket packet = new DatagramPacket(data, data.length, address, getPort()); socket.send(packet); Thread.sleep(100); } } finally { socket.close(); } }
37. MulticastSender#main()
Project: axis2-java
File: MulticastSender.java
File: MulticastSender.java
public static void main(String[] args) throws Exception { // Multicast send byte[] outbuf = "Hello world".getBytes(); DatagramSocket socket = null; try { socket = new DatagramSocket(); InetAddress groupAddr = InetAddress.getByName(ip); DatagramPacket packet = new DatagramPacket(outbuf, outbuf.length, groupAddr, port); socket.send(packet); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (socket != null) { socket.close(); } } System.out.println("Sent"); }
38. LENonTerminateTest#mockServer()
Project: zookeeper
File: LENonTerminateTest.java
File: LENonTerminateTest.java
/** * MockServer plays the role of peer C. Respond to two requests for votes * with vote for self and then Assert.fail. */ void mockServer() throws InterruptedException, IOException { byte b[] = new byte[36]; ByteBuffer responseBuffer = ByteBuffer.wrap(b); DatagramPacket packet = new DatagramPacket(b, b.length); QuorumServer server = peers.get(Long.valueOf(2)); DatagramSocket udpSocket = new DatagramSocket(server.addr.getPort()); LOG.info("In MockServer"); mockLatch.countDown(); Vote current = new Vote(2, 1); for (int i = 0; i < 2; ++i) { udpSocket.receive(packet); responseBuffer.rewind(); LOG.info("Received " + responseBuffer.getInt() + " " + responseBuffer.getLong() + " " + responseBuffer.getLong()); LOG.info("From " + packet.getSocketAddress()); responseBuffer.clear(); // Skip the xid responseBuffer.getInt(); responseBuffer.putLong(2); responseBuffer.putLong(current.getId()); responseBuffer.putLong(current.getZxid()); packet.setData(b); udpSocket.send(packet); } }
39. UDPTransportHandler#initialize()
Project: TLS-Attacker
File: UDPTransportHandler.java
File: UDPTransportHandler.java
@Override public void initialize(String remoteAddress, int remotePort) throws IOException { datagramSocket = new DatagramSocket(); datagramSocket.setSoTimeout(DEFAULT_TLS_TIMEOUT); datagramSocket.connect(InetAddress.getByName(remoteAddress), remotePort); sentPacket = new DatagramPacket(new byte[0], 0, datagramSocket.getInetAddress(), datagramSocket.getPort()); if (LOGGER.isDebugEnabled()) { StringBuilder logOut = new StringBuilder(); logOut.append("Socket bound to \""); logOut.append(datagramSocket.getLocalAddress().getCanonicalHostName()); logOut.append(":"); logOut.append(datagramSocket.getLocalPort()); logOut.append("\". Specified remote host and port: \""); logOut.append(datagramSocket.getInetAddress().getCanonicalHostName()); logOut.append(":"); logOut.append(datagramSocket.getPort()); logOut.append("\"."); LOGGER.debug(logOut.toString()); } }
40. AudioMediaSession#createSession()
Project: Smack
File: AudioMediaSession.java
File: AudioMediaSession.java
/** * Create a Session using Speex Codec. * * @param localhost localHost * @param localPort localPort * @param remoteHost remoteHost * @param remotePort remotePort * @param eventHandler eventHandler * @param quality quality * @param secure secure * @param micOn micOn * @return MediaSession * @throws NoProcessorException * @throws UnsupportedFormatException * @throws IOException * @throws GeneralSecurityException */ public static MediaSession createSession(String localhost, int localPort, String remoteHost, int remotePort, MediaSessionListener eventHandler, int quality, boolean secure, boolean micOn) throws NoProcessorException, UnsupportedFormatException, IOException, GeneralSecurityException { SpeexFormat.setFramesPerPacket(1); /** * The master key. Hardcoded for now. */ byte[] masterKey = new byte[] { (byte) 0xE1, (byte) 0xF9, 0x7A, 0x0D, 0x3E, 0x01, (byte) 0x8B, (byte) 0xE0, (byte) 0xD6, 0x4F, (byte) 0xA3, 0x2C, 0x06, (byte) 0xDE, 0x41, 0x39 }; /** * The master salt. Hardcoded for now. */ byte[] masterSalt = new byte[] { 0x0E, (byte) 0xC6, 0x75, (byte) 0xAD, 0x49, (byte) 0x8A, (byte) 0xFE, (byte) 0xEB, (byte) 0xB6, (byte) 0x96, 0x0B, 0x3A, (byte) 0xAB, (byte) 0xE6 }; DatagramSocket[] localPorts = MediaSession.getLocalPorts(InetAddress.getByName(localhost), localPort); MediaSession session = MediaSession.createInstance(remoteHost, remotePort, localPorts, quality, secure, masterKey, masterSalt); session.setListener(eventHandler); session.setSourceDescription(new SourceDescription[] { new SourceDescription(SourceDescription.SOURCE_DESC_NAME, "Superman", 1, false), new SourceDescription(SourceDescription.SOURCE_DESC_EMAIL, "[email protected]", 1, false), new SourceDescription(SourceDescription.SOURCE_DESC_LOC, InetAddress.getByName(localhost) + " Port " + session.getLocalDataPort(), 1, false), new SourceDescription(SourceDescription.SOURCE_DESC_TOOL, "JFCOM CDCIE Audio Chat", 1, false) }); return session; }
41. UPNPHelper#sendReply()
Project: ps3mediaserver
File: UPNPHelper.java
File: UPNPHelper.java
/** * Send reply. * * @param host the host * @param port the port * @param msg the msg * @throws IOException Signals that an I/O exception has occurred. */ private static void sendReply(String host, int port, String msg) { DatagramSocket datagramSocket = null; try { datagramSocket = new DatagramSocket(); InetAddress inetAddr = InetAddress.getByName(host); DatagramPacket dgmPacket = new DatagramPacket(msg.getBytes(), msg.length(), inetAddr, port); logger.trace("Sending this reply [" + host + ":" + port + "]: " + StringUtils.replace(msg, CRLF, "<CRLF>")); datagramSocket.send(dgmPacket); } catch (Exception e) { logger.info(e.getMessage()); logger.debug("Error sending reply", e); } finally { if (datagramSocket != null) { datagramSocket.close(); } } }
42. UDPChecker#check()
Project: pinpoint
File: UDPChecker.java
File: UDPChecker.java
@Override protected boolean check(InetSocketAddress address, byte[] requestData, byte[] expectedResponseData) { DatagramSocket socket = null; try { socket = createSocket(address); write(socket, requestData); byte[] responseData = read(socket, expectedResponseData.length); return Arrays.equals(expectedResponseData, responseData); } catch (IOException e) { e.printStackTrace(); } finally { if (socket != null) { socket.close(); } } return false; }
43. UDPChecker#check()
Project: pinpoint
File: UDPChecker.java
File: UDPChecker.java
@Override protected boolean check(InetSocketAddress address) throws IOException { DatagramSocket socket = null; try { socket = createSocket(address); return socket.isConnected(); } catch (IOException e) { e.printStackTrace(); } finally { if (socket != null) { socket.close(); } } return false; }
44. TestUDPReceiver#start()
Project: pinpoint
File: TestUDPReceiver.java
File: TestUDPReceiver.java
@PostConstruct @Override public void start() { logger.info("{} start.", receiverName); afterPropertiesSet(); final DatagramSocket socket = this.socket; if (socket == null) { throw new IllegalStateException("socket is null."); } bindSocket(socket, bindAddress, port); logger.info("UDP Packet reader:{} started.", ioThreadSize); for (int i = 0; i < ioThreadSize; i++) { io.execute(new Runnable() { @Override public void run() { receive(socket); } }); } }
45. UDPReceiver#start()
Project: pinpoint
File: UDPReceiver.java
File: UDPReceiver.java
@PostConstruct @Override public void start() { logger.info("{} start.", receiverName); afterPropertiesSet(); final DatagramSocket socket = this.socket; if (socket == null) { throw new IllegalStateException("socket is null."); } bindSocket(socket, bindAddress, port); logger.info("UDP Packet reader:{} started.", ioThreadSize); for (int i = 0; i < ioThreadSize; i++) { io.execute(new Runnable() { @Override public void run() { receive(socket); } }); } }
46. UdpSocketTest#testRemoteSend()
Project: pinpoint
File: UdpSocketTest.java
File: UdpSocketTest.java
// @Test public void testRemoteSend() throws IOException, InterruptedException { DatagramSocket so = new DatagramSocket(); so.connect(new InetSocketAddress("10.66.18.78", PORT)); so.send(newDatagramPacket(1500)); so.send(newDatagramPacket(10000)); so.send(newDatagramPacket(20000)); so.send(newDatagramPacket(50000)); so.send(newDatagramPacket(60000)); so.send(newDatagramPacket(AcceptedSize)); try { so.send(newDatagramPacket(AcceptedSize + 1)); Assert.fail("failed"); } catch (IOException ignore) { } try { so.send(newDatagramPacket(70000)); Assert.fail("failed"); } catch (IOException ignore) { } so.close(); }
47. BadKdc#go0()
Project: openjdk
File: BadKdc.java
File: BadKdc.java
public static void go0(String... expected) throws Exception { System.setProperty("sun.security.krb5.debug", "true"); // Idle UDP sockets will trigger a SocketTimeoutException, without it, // a PortUnreachableException will be thrown. DatagramSocket d1 = null, d2 = null, d3 = null; // Make sure KDCs' ports starts with 1 and 2 and 3, // useful for checking debug output. int p1 = 10000 + new java.util.Random().nextInt(10000); int p2 = 20000 + new java.util.Random().nextInt(10000); int p3 = 30000 + new java.util.Random().nextInt(10000); FileWriter fw = new FileWriter("alternative-krb5.conf"); fw.write("[libdefaults]\n" + "default_realm = " + OneKDC.REALM + "\n" + "kdc_timeout = " + toReal(2000) + "\n"); fw.write("[realms]\n" + OneKDC.REALM + " = {\n" + "kdc = " + OneKDC.KDCHOST + ":" + p1 + "\n" + "kdc = " + OneKDC.KDCHOST + ":" + p2 + "\n" + "kdc = " + OneKDC.KDCHOST + ":" + p3 + "\n" + "}\n"); fw.close(); System.setProperty("java.security.krb5.conf", "alternative-krb5.conf"); Config.refresh(); // Turn on k3 only d1 = new DatagramSocket(p1); d2 = new DatagramSocket(p2); KDC k3 = on(p3); test(expected[0]); test(expected[1]); Config.refresh(); test(expected[2]); // shutdown k3 k3.terminate(); d3 = new DatagramSocket(p3); d2.close(); // k2 is on on(p2); test(expected[3]); d1.close(); // k1 and k2 is on on(p1); test(expected[4]); d3.close(); }
48. NtpClient#getOffset()
Project: railo
File: NtpClient.java
File: NtpClient.java
/** * returns the offest from the ntp server to local system * @return * @throws IOException */ public long getOffset() throws IOException { /// Send request DatagramSocket socket = new DatagramSocket(); socket.setSoTimeout(10000); InetAddress address = InetAddress.getByName(serverName); byte[] buf = new NtpMessage().toByteArray(); DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 123); // Set the transmit timestamp *just* before sending the packet NtpMessage.encodeTimestamp(packet.getData(), 40, (System.currentTimeMillis() / 1000.0) + 2208988800.0); socket.send(packet); // Get response packet = new DatagramPacket(buf, buf.length); socket.receive(packet); // Immediately record the incoming timestamp double destinationTimestamp = (System.currentTimeMillis() / 1000.0) + 2208988800.0; // Process response NtpMessage msg = new NtpMessage(packet.getData()); //double roundTripDelay = (destinationTimestamp-msg.originateTimestamp) - (msg.receiveTimestamp-msg.transmitTimestamp); double localClockOffset = ((msg.receiveTimestamp - msg.originateTimestamp) + (msg.transmitTimestamp - destinationTimestamp)) / 2; return (long) (localClockOffset * 1000); }
49. UDPReceiverTest#sendSocketBufferSize()
Project: pinpoint
File: UDPReceiverTest.java
File: UDPReceiverTest.java
@Test public void sendSocketBufferSize() throws IOException { DatagramPacket datagramPacket = new DatagramPacket(new byte[0], 0, 0); DatagramSocket datagramSocket = new DatagramSocket(); datagramSocket.connect(new InetSocketAddress("127.0.0.1", 9995)); datagramSocket.send(datagramPacket); datagramSocket.close(); }
50. UDPTransportHandlerTest#testFetchData()
Project: TLS-Attacker
File: UDPTransportHandlerTest.java
File: UDPTransportHandlerTest.java
@Test public void testFetchData() throws Exception { UDPTransportHandler udpTH = new UDPTransportHandler(); DatagramSocket testSocket = new DatagramSocket(); udpTH.initialize(localhost.getHostName(), testSocket.getLocalPort()); testSocket.connect(localhost, udpTH.getLocalPort()); udpTH.setTlsTimeout(1); byte[] allSentData = new byte[0]; byte[] allReceivedData = new byte[0]; byte[] txData; byte[] rxData; DatagramPacket txPacket; int numTestPackets = 100; for (int i = 0; i < numTestPackets; i++) { txData = new byte[RandomHelper.getRandom().nextInt(16383) + 1]; RandomHelper.getRandom().nextBytes(txData); txPacket = new DatagramPacket(txData, txData.length, localhost, udpTH.getLocalPort()); testSocket.send(txPacket); allSentData = ArrayConverter.concatenate(allSentData, txData); rxData = udpTH.fetchData(); allReceivedData = ArrayConverter.concatenate(allReceivedData, rxData); } assertEquals("Confirm size of the received data", allSentData.length, allReceivedData.length); assertArrayEquals("Confirm received data equals sent data", allSentData, allReceivedData); udpTH.closeConnection(); testSocket.close(); }
51. UDPChecker#createSocket()
Project: pinpoint
File: UDPChecker.java
File: UDPChecker.java
private DatagramSocket createSocket(InetSocketAddress socketAddress) throws IOException { DatagramSocket socket = new DatagramSocket(); socket.connect(socketAddress); socket.setSoTimeout(3000); return socket; }
52. UDPReceiverTest#socketBufferSize()
Project: pinpoint
File: UDPReceiverTest.java
File: 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(); }
53. TestBufferingWrappers#resendAfterStop()
Project: HiTune
File: TestBufferingWrappers.java
File: TestBufferingWrappers.java
//start a wrapped FileAdaptor. Pushes a chunk. Stop it and restart. //chunk hasn't been acked, so should get pushed again. //we delete the file and also change the data type each time through the loop //to make sure we get the cached chunk. public void resendAfterStop(String adaptor) throws IOException, ChukwaAgent.AlreadyRunningException, InterruptedException { ChukwaAgent agent = new ChukwaAgent(conf); String ADAPTORID = "adaptor_test" + System.currentTimeMillis(); String STR = "test data"; int PORTNO = 9878; DatagramSocket send = new DatagramSocket(); byte[] buf = STR.getBytes(); DatagramPacket p = new DatagramPacket(buf, buf.length); p.setSocketAddress(new InetSocketAddress("127.0.0.1", PORTNO)); assertEquals(0, agent.adaptorCount()); String name = agent.processAddCommand("add " + ADAPTORID + " = " + adaptor + " UDPAdaptor raw " + PORTNO + " 0"); assertEquals(name, ADAPTORID); Thread.sleep(500); send.send(p); for (int i = 0; i < 5; ++i) { Chunk c = chunks.waitForAChunk(5000); System.out.println("received " + i); assertNotNull(c); String dat = new String(c.getData()); assertTrue(dat.equals(STR)); assertTrue(c.getDataType().equals("raw")); assertEquals(c.getSeqID(), STR.length()); agent.stopAdaptor(name, AdaptorShutdownPolicy.RESTARTING); //for socket to deregister Thread.sleep(500); name = agent.processAddCommand("add " + ADAPTORID + " = " + adaptor + " UDPAdaptor raw " + PORTNO + " 0"); assertEquals(name, ADAPTORID); } Chunk c = chunks.waitForAChunk(5000); Thread.sleep(500); buf = "different data".getBytes(); p = new DatagramPacket(buf, buf.length); p.setSocketAddress(new InetSocketAddress("127.0.0.1", PORTNO)); send.send(p); c = chunks.waitForAChunk(5000); assertNotNull(c); assertEquals(buf.length + STR.length(), c.getSeqID()); agent.stopAdaptor(name, true); assertEquals(0, agent.adaptorCount()); //before re-binding Thread.sleep(500); agent.shutdown(); }
54. TestUDPToKafkaSource#sendDatagram()
Project: datacollector
File: TestUDPToKafkaSource.java
File: TestUDPToKafkaSource.java
private void sendDatagram(byte[] data, int port) throws Exception { DatagramSocket clientSocket = new DatagramSocket(); InetAddress address = InetAddress.getLoopbackAddress(); DatagramPacket sendPacket = new DatagramPacket(data, data.length, address, port); clientSocket.send(sendPacket); clientSocket.close(); }
55. DTLSServerTest#main()
Project: bc-java
File: DTLSServerTest.java
File: DTLSServerTest.java
public static void main(String[] args) throws Exception { int port = 5556; int mtu = 1500; SecureRandom secureRandom = new SecureRandom(); DTLSServerProtocol serverProtocol = new DTLSServerProtocol(secureRandom); byte[] data = new byte[mtu]; DatagramPacket packet = new DatagramPacket(data, mtu); DatagramSocket socket = new DatagramSocket(port); socket.receive(packet); System.out.println("Accepting connection from " + packet.getAddress().getHostAddress() + ":" + port); socket.connect(packet.getAddress(), packet.getPort()); /* * NOTE: For simplicity, and since we don't yet have HelloVerifyRequest support, we just * discard the initial packet, which the client should re-send anyway. */ DatagramTransport transport = new UDPTransport(socket, mtu); // Uncomment to see packets // transport = new LoggingDatagramTransport(transport, System.out); MockDTLSServer server = new MockDTLSServer(); DTLSTransport dtlsServer = serverProtocol.accept(server, transport); byte[] buf = new byte[dtlsServer.getReceiveLimit()]; while (!socket.isClosed()) { try { int length = dtlsServer.receive(buf, 0, buf.length, 60000); if (length >= 0) { System.out.write(buf, 0, length); dtlsServer.send(buf, 0, length); } } catch (SocketTimeoutException ste) { } } dtlsServer.close(); }
56. UdpClientTest#choosePort()
Project: ribbon
File: UdpClientTest.java
File: UdpClientTest.java
public int choosePort() throws SocketException { DatagramSocket serverSocket = new DatagramSocket(); int port = serverSocket.getLocalPort(); serverSocket.close(); return port; }
57. HelloUdpServerExternalResource#choosePort()
Project: ribbon
File: HelloUdpServerExternalResource.java
File: HelloUdpServerExternalResource.java
private int choosePort() throws SocketException { DatagramSocket serverSocket = new DatagramSocket(); int port = serverSocket.getLocalPort(); serverSocket.close(); return port; }
58. UdpSocketTest#setUp()
Project: pinpoint
File: UdpSocketTest.java
File: UdpSocketTest.java
@Before public void setUp() throws SocketException { receiver = new DatagramSocket(PORT); sender = new DatagramSocket(); sender.connect(new InetSocketAddress("localhost", PORT)); }
59. NetUtil#getHostAddress()
Project: pinot
File: NetUtil.java
File: NetUtil.java
/** * Get the ip address of local host. */ public static String getHostAddress() throws SocketException, UnknownHostException { DatagramSocket ds = new DatagramSocket(); ds.connect(InetAddress.getByName(DUMMY_OUT_IP), 80); InetAddress localAddress = ds.getLocalAddress(); if (localAddress.getHostAddress().equals("0.0.0.0")) { localAddress = InetAddress.getLocalHost(); } return localAddress.getHostAddress(); }
60. MaxRetries#main()
Project: openjdk
File: MaxRetries.java
File: MaxRetries.java
public static void main(String[] args) throws Exception { System.setProperty("sun.security.krb5.debug", "true"); new OneKDC(null).writeJAASConf(); // An idle UDP socket to prevent PortUnreachableException DatagramSocket ds = new DatagramSocket(); idlePort = ds.getLocalPort(); System.setProperty("java.security.krb5.conf", "alternative-krb5.conf"); // For tryLast Security.setProperty("krb5.kdc.bad.policy", "trylast"); rewriteMaxRetries(4); // 1 1 1 1 2 2 test1(4000, 6); // 2 2 test1(4000, 2); rewriteMaxRetries(1); // 1 2 2 test1(1000, 3); // 2 2 test1(1000, 2); rewriteMaxRetries(-1); // 1 1 2 2 test1(5000, 4); // 2 2 test1(5000, 2); // For tryLess Security.setProperty("krb5.kdc.bad.policy", "tryless:1," + BadKdc.toReal(5000)); rewriteMaxRetries(4); // 1 1 1 1 2 1 2 test1(4000, 7); // 1 2 1 2 test1(4000, 4); rewriteMaxRetries(1); // 1 2 1 2 test1(1000, 4); // 1 2 1 2 test1(1000, 4); rewriteMaxRetries(-1); // 1 1 2 1 2 test1(5000, 5); // 1 2 1 2 test1(5000, 4); // default, no limit rewriteUdpPrefLimit(-1, -1); test2("UDP"); // global rules rewriteUdpPrefLimit(10, -1); test2("TCP"); // realm rules rewriteUdpPrefLimit(10, 10000); test2("UDP"); // realm rules rewriteUdpPrefLimit(10000, 10); test2("TCP"); ds.close(); }
61. PortUnreachable#execute()
Project: openjdk
File: PortUnreachable.java
File: PortUnreachable.java
void execute() throws Exception { // pick a port for the server DatagramSocket sock2 = new DatagramSocket(); serverPort = sock2.getLocalPort(); // send a burst of packets to the unbound port - we should get back // icmp port unreachable messages // InetAddress addr = InetAddress.getLocalHost(); byte b[] = "Hello me".getBytes(); DatagramPacket packet = new DatagramPacket(b, b.length, addr, serverPort); //close just before sending sock2.close(); for (int i = 0; i < 100; i++) clientSock.send(packet); serverSend(); // try to receive b = new byte[25]; packet = new DatagramPacket(b, b.length, addr, serverPort); clientSock.setSoTimeout(10000); clientSock.receive(packet); System.out.println("client received data packet " + new String(packet.getData())); // done clientSock.close(); }
62. InheritHandle#main()
Project: openjdk
File: InheritHandle.java
File: InheritHandle.java
public static void main(String[] args) throws Exception { int port; try (DatagramSocket sock = new DatagramSocket(0)) { sock.setReuseAddress(true); port = sock.getLocalPort(); /** * spawn a child to check whether handle passed to it or not; it * shouldn't */ Runtime.getRuntime().exec("sleep 10"); } try (DatagramSocket sock = new DatagramSocket(null)) { sock.setReuseAddress(true); int retries = 0; boolean isWindows = System.getProperty("os.name").startsWith("Windows"); InetSocketAddress addr = new InetSocketAddress(port); while (true) { try { sock.bind(addr); break; } catch (BindException e) { if (isWindows && retries++ < 5) { Thread.sleep(SLEEPTIME_MS); System.out.println("BindException \"" + e.getMessage() + "\", retrying..."); continue; } else { throw e; } } } } }
63. MaxCubeDiscover#discoverIp()
Project: openhab
File: MaxCubeDiscover.java
File: MaxCubeDiscover.java
/** * Automatic UDP discovery of a MAX!Cube * * @return if the cube is found, returns the IP address as a string. Otherwise returns null */ public static final String discoverIp() { String maxCubeIP = null; String maxCubeName = null; String rfAddress = null; Logger logger = LoggerFactory.getLogger(MaxCubeDiscover.class); DatagramSocket bcReceipt = null; DatagramSocket bcSend = null; // Find the MaxCube using UDP broadcast try { bcSend = new DatagramSocket(); bcSend.setBroadcast(true); byte[] sendData = "eQ3Max*\0**********I".getBytes(); // Broadcast the message over all the network interfaces Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); if (networkInterface.isLoopback() || !networkInterface.isUp()) { continue; } for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) { InetAddress[] broadcast = new InetAddress[2]; broadcast[0] = InetAddress.getByName("224.0.0.1"); broadcast[1] = interfaceAddress.getBroadcast(); for (InetAddress bc : broadcast) { // Send the broadcast package! if (bc != null) { try { DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, bc, 23272); bcSend.send(sendPacket); } catch (IOException e) { logger.debug("IO error during MAX! Cube discovery: {}", e.getMessage()); } catch (Exception e) { logger.debug(e.getMessage()); logger.debug(Utils.getStackTrace(e)); } logger.trace("Request packet sent to: {} Interface: {}", bc.getHostAddress(), networkInterface.getDisplayName()); } } } } logger.trace("Done looping over all network interfaces. Now waiting for a reply!"); bcSend.close(); bcReceipt = new DatagramSocket(23272); bcReceipt.setReuseAddress(true); // Wait for a response byte[] recvBuf = new byte[15000]; DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length); bcReceipt.receive(receivePacket); // We have a response logger.trace("Broadcast response from server: {}", receivePacket.getAddress()); // Check if the message is correct String message = new String(receivePacket.getData()).trim(); if (message.startsWith("eQ3Max")) { maxCubeIP = receivePacket.getAddress().getHostAddress(); maxCubeName = message.substring(0, 8); rfAddress = message.substring(8, 18); logger.debug("Found at: {}", maxCubeIP); logger.debug("Name : {}", maxCubeName); logger.debug("Serial : {}", rfAddress); logger.trace("Message : {}", message); } else { logger.info("No Max!Cube gateway found on network"); } } catch (IOException e) { logger.debug("IO error during MAX! Cube discovery: {}", e.getMessage()); } catch (Exception e) { logger.debug(e.getMessage()); logger.debug(Utils.getStackTrace(e)); } finally { try { if (bcReceipt != null) { bcReceipt.close(); } } catch (Exception e) { logger.debug(e.toString()); } try { if (bcSend != null) { bcSend.close(); } } catch (Exception e) { logger.debug(e.toString()); } } return maxCubeIP; }
64. DatagramLoggingActivityFactoryTest#testPropertyPriority()
Project: oodt
File: DatagramLoggingActivityFactoryTest.java
File: DatagramLoggingActivityFactoryTest.java
/** * Test use of the system properties. * * @throws SocketException if an error occurs. */ public void testPropertyPriority() throws SocketException { System.getProperties().remove("org.apache.oodt.commons.activity.DatagramLoggingActivityFactory.host"); System.getProperties().remove("org.apache.oodt.commons.activity.DatagramLoggingActivityFactory.port"); System.getProperties().remove("activity.host"); System.getProperties().remove("activity.port"); try { new DatagramLoggingActivityFactory(); fail("Can make a DatagramLoggingActivityFactory without host property set"); } catch (IllegalStateException ignored) { } System.setProperty("org.apache.oodt.commons.activity.DatagramLoggingActivityFactory.host", "localhost"); System.setProperty("activity.host", "non-existent-host"); DatagramLoggingActivityFactory fac = new DatagramLoggingActivityFactory(); assertEquals(org.apache.oodt.commons.net.Net.getLoopbackAddress(), fac.host); assertEquals(4556, fac.port); fac.socket.close(); System.getProperties().remove("org.apache.oodt.commons.activity.DatagramLoggingActivityFactory.host"); System.setProperty("activity.host", "localhost"); fac = new DatagramLoggingActivityFactory(); assertEquals(org.apache.oodt.commons.net.Net.getLoopbackAddress(), fac.host); assertEquals(4556, fac.port); fac.socket.close(); DatagramSocket soc = new DatagramSocket(); int portNum = soc.getLocalPort(); System.setProperty("org.apache.oodt.commons.activity.DatagramLoggingActivityFactory.port", String.valueOf(portNum)); System.setProperty("activity.port", "illegal-port-value"); fac = new DatagramLoggingActivityFactory(); assertEquals(portNum, fac.port); fac.socket.close(); System.getProperties().remove("org.apache.oodt.commons.activity.DatagramLoggingActivityFactory.port"); System.setProperty("activity.port", String.valueOf(portNum)); fac = new DatagramLoggingActivityFactory(); assertEquals(portNum, fac.port); fac.socket.close(); soc.close(); }
65. NioUdpClientFilterEventTest#generate_all_kind_of_client_event()
Project: mina
File: NioUdpClientFilterEventTest.java
File: NioUdpClientFilterEventTest.java
/** * Create an old IO server and use a bunch of MINA client on it. Test if the * events occurs correctly in the different IoFilters. */ @Test public void generate_all_kind_of_client_event() throws IOException, InterruptedException, ExecutionException { NioUdpClient client = new NioUdpClient(); client.getSessionConfig().setIdleTimeInMillis(IdleStatus.READ_IDLE, 2000); client.setFilters(new MyCodec(), new Handler()); DatagramSocket serverSocket = new DatagramSocket(); int port = serverSocket.getLocalPort(); // warm up Thread.sleep(100); final long t0 = System.currentTimeMillis(); // now connect the clients List<IoFuture<IoSession>> cf = new ArrayList<IoFuture<IoSession>>(); for (int i = 0; i < CLIENT_COUNT; i++) { cf.add(client.connect(new InetSocketAddress("localhost", port))); } // does the session open message was fired ? assertTrue(openLatch.await(WAIT_TIME, TimeUnit.MILLISECONDS)); // gather sessions from futures IoSession[] sessions = new IoSession[CLIENT_COUNT]; for (int i = 0; i < CLIENT_COUNT; i++) { sessions[i] = cf.get(i).get(); assertNotNull(sessions[i]); } // receive and send back some message for (int i = 0; i < CLIENT_COUNT; i++) { byte[] receiveData = new byte[1024]; DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); String sentence = new String(receivePacket.getData()); LOG.info("RECEIVED :" + sentence); InetAddress IPAddress = receivePacket.getAddress(); int clientPort = receivePacket.getPort(); DatagramPacket sendPacket = new DatagramPacket("tata".getBytes(), "tata".getBytes().length, IPAddress, clientPort); serverSocket.send(sendPacket); } // does response was wrote and sent ? assertTrue(msgSentLatch.await(WAIT_TIME, TimeUnit.MILLISECONDS)); // test is message was received by the client assertTrue(msgReadLatch.await(WAIT_TIME, TimeUnit.MILLISECONDS)); // the session idled assertEquals(CLIENT_COUNT, idleLatch.getCount()); // close the session assertEquals(CLIENT_COUNT, closedLatch.getCount()); serverSocket.close(); // does the session close event was fired ? assertTrue(closedLatch.await(WAIT_TIME, TimeUnit.MILLISECONDS)); long t1 = System.currentTimeMillis(); System.out.println("Delta = " + (t1 - t0)); }
66. SyslogAppenderTest#testLeak()
Project: log4j
File: SyslogAppenderTest.java
File: SyslogAppenderTest.java
public void testLeak() throws IOException { DatagramSocket ds = new DatagramSocket(); for (int i = 0; i < 100; i++) { SyslogWriter sw = new SyslogWriter("localhost:" + ds.getLocalPort()); sw.close(); } ds.close(); }
67. RTKInterface#dispatchUDPPacket()
Project: jsonapi
File: RTKInterface.java
File: RTKInterface.java
private void dispatchUDPPacket(String packet, String host, int port) throws IOException { final Object lock = this; lastResponse = null; final DatagramSocket ds = new DatagramSocket(); DatagramPacket dp; try { dp = new DatagramPacket(packet.getBytes(), packet.getBytes("UTF-8").length, InetAddress.getByName(host), port); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return; } ds.send(dp); new Thread() { public void run() { byte[] buffer = new byte[65536]; DatagramPacket incoming = new DatagramPacket(buffer, buffer.length); try { ds.setSoTimeout(5000); ds.receive(incoming); String temp = new String(incoming.getData()); setResponse(temp.trim()); } catch (SocketTimeoutException e) { setResponse("timeout"); } catch (Exception e) { System.err.println("Unexpected Socket error: " + e); e.printStackTrace(); } synchronized (lock) { lock.notifyAll(); } } }.start(); }
68. DatagramSocketFactory#makeObject()
Project: jmxtrans
File: DatagramSocketFactory.java
File: DatagramSocketFactory.java
/** * Creates the socket and the writer to go with it. */ @Override public DatagramSocket makeObject(SocketAddress socketAddress) throws Exception { DatagramSocket datagramSocket = new DatagramSocket(); datagramSocket.connect(socketAddress); return datagramSocket; }
69. UDPBroadcastThreadTest#legacy()
Project: Jenkins2
File: UDPBroadcastThreadTest.java
File: UDPBroadcastThreadTest.java
/** * Old unicast based clients should still be able to receive some reply, * as we haven't changed the port. */ @Test public void legacy() throws Exception { DatagramSocket s = new DatagramSocket(); sendQueryTo(s, InetAddress.getLocalHost()); // to prevent test hang s.setSoTimeout(15000); try { receiveAndVerify(s); } catch (SocketTimeoutException x) { Assume.assumeFalse(UDPBroadcastThread.udpHandlingProblem); throw x; } }
70. DatagramSocketTest#testStateAfterClose()
Project: j2objc
File: DatagramSocketTest.java
File: DatagramSocketTest.java
public void testStateAfterClose() throws Exception { DatagramSocket ds = new DatagramSocket(); ds.close(); assertTrue(ds.isBound()); assertTrue(ds.isClosed()); assertFalse(ds.isConnected()); assertNull(ds.getLocalAddress()); assertEquals(-1, ds.getLocalPort()); assertNull(ds.getLocalSocketAddress()); }
71. UDPBroadcastThreadTest#legacy()
Project: hudson
File: UDPBroadcastThreadTest.java
File: UDPBroadcastThreadTest.java
/** * Old unicast based clients should still be able to receive some reply, * as we haven't changed the port. */ @Test public void legacy() throws Exception { DatagramSocket s = new DatagramSocket(); sendQueryTo(s, InetAddress.getLocalHost()); // to prevent test hang s.setSoTimeout(15000); try { receiveAndVerify(s); } catch (SocketTimeoutException x) { Assume.assumeFalse(UDPBroadcastThread.udpHandlingProblem); throw x; } }
72. UdpConnection#setupSocket()
Project: etch
File: UdpConnection.java
File: UdpConnection.java
@Override protected void setupSocket() throws Exception { DatagramSocket s = checkSocket(); s.setTrafficClass(trafficClass); }
73. GdmHandler#getServers()
Project: plex-client
File: GdmHandler.java
File: GdmHandler.java
public static List<PlexMediaServer> getServers() { List<PlexMediaServer> servers = new ArrayList<>(); try (DatagramSocket socket = new DatagramSocket(32414)) { socket.setBroadcast(true); String data = "M-SEARCH * HTTP/1.1\r\n\r\n"; DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(), InetAddress.getByName(multicast), 32414); socket.send(packet); byte[] buf = new byte[512]; packet = new DatagramPacket(buf, buf.length); socket.setSoTimeout(1000); boolean listening = true; while (listening) { try { socket.receive(packet); String packetData = new String(packet.getData()); if (packetData.contains("HTTP/1.0 200 OK")) { servers.add(parseGdmResponse(packetData)); } } catch (SocketTimeoutException e) { listening = false; } } } catch (IOException e) { System.err.println(e); } return servers; }
74. NioUdpDataSenderTest#setUp()
Project: pinpoint
File: NioUdpDataSenderTest.java
File: NioUdpDataSenderTest.java
@Before public void setUp() throws SocketException { receiver = new DatagramSocket(PORT); receiver.setSoTimeout(1000); }
75. SpanStreamUdpSender#createChannel()
Project: pinpoint
File: SpanStreamUdpSender.java
File: SpanStreamUdpSender.java
private DatagramChannel createChannel(String host, int port, int timeout, int sendBufferSize) { DatagramChannel datagramChannel = null; DatagramSocket socket = null; try { datagramChannel = DatagramChannel.open(); socket = datagramChannel.socket(); socket.setSoTimeout(timeout); socket.setSendBufferSize(sendBufferSize); if (logger.isWarnEnabled()) { final int checkSendBufferSize = socket.getSendBufferSize(); if (sendBufferSize != checkSendBufferSize) { logger.warn("DatagramChannel.setSendBufferSize() error. {}!={}", sendBufferSize, checkSendBufferSize); } } InetSocketAddress serverAddress = new InetSocketAddress(host, port); datagramChannel.connect(serverAddress); return datagramChannel; } catch (IOException e) { if (socket != null) { socket.close(); } if (datagramChannel != null) { try { datagramChannel.close(); } catch (IOException ignored) { } } throw new IllegalStateException("DatagramChannel create fail. Cause" + e.getMessage(), e); } }
76. NioUDPDataSender#createChannel()
Project: pinpoint
File: NioUDPDataSender.java
File: NioUDPDataSender.java
private DatagramChannel createChannel(String host, int port, int timeout, int sendBufferSize) { DatagramChannel datagramChannel = null; DatagramSocket socket = null; try { datagramChannel = DatagramChannel.open(); socket = datagramChannel.socket(); socket.setSoTimeout(timeout); socket.setSendBufferSize(sendBufferSize); if (logger.isWarnEnabled()) { final int checkSendBufferSize = socket.getSendBufferSize(); if (sendBufferSize != checkSendBufferSize) { logger.warn("DatagramChannel.setSendBufferSize() error. {}!={}", sendBufferSize, checkSendBufferSize); } } InetSocketAddress serverAddress = new InetSocketAddress(host, port); datagramChannel.connect(serverAddress); return datagramChannel; } catch (IOException e) { if (socket != null) { socket.close(); } if (datagramChannel != null) { try { datagramChannel.close(); } catch (IOException ignored) { } } throw new IllegalStateException("DatagramChannel create fail. Cause" + e.getMessage(), e); } }
77. NetworkAvailabilityCheckPacketFilterTest#setUp()
Project: pinpoint
File: NetworkAvailabilityCheckPacketFilterTest.java
File: NetworkAvailabilityCheckPacketFilterTest.java
@Before public void setUp() throws Exception { filter = new NetworkAvailabilityCheckPacketFilter(); datagramSocket = new DatagramSocket(0); }
78. SocketPermissionTest#sendDatagramPacketTest()
Project: openjdk
File: SocketPermissionTest.java
File: SocketPermissionTest.java
@Test public void sendDatagramPacketTest() throws Exception { byte[] msg = "Hello".getBytes(UTF_8); InetAddress group = InetAddress.getByName("229.227.226.221"); try (DatagramSocket ds = new DatagramSocket(0)) { int port = ds.getLocalPort(); String addr = "localhost:" + port; //test for SocketPermission "229.227.226.221", "connect,accept" AccessControlContext acc = getAccessControlContext(new SocketPermission(addr, "listen,resolve"), new SocketPermission("229.227.226.221", "connect,accept")); // Positive AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> { DatagramPacket hi = new DatagramPacket(msg, msg.length, group, port); ds.send(hi); return null; }, acc); // Negative try { AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> { DatagramPacket hi = new DatagramPacket(msg, msg.length, group, port); ds.send(hi); fail("Expected SecurityException"); return null; }, RESTRICTED_ACC); } catch (SecurityException expected) { } } }
79. SocketPermissionTest#connectDatagramSocketTest()
Project: openjdk
File: SocketPermissionTest.java
File: SocketPermissionTest.java
@Test public void connectDatagramSocketTest() throws Exception { byte[] msg = "Hello".getBytes(UTF_8); InetAddress lh = InetAddress.getLocalHost(); try (DatagramSocket ds = new DatagramSocket(0)) { int port = ds.getLocalPort(); String addr = lh.getHostAddress() + ":" + port; AccessControlContext acc = getAccessControlContext(new SocketPermission(addr, "connect,resolve")); // Positive AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> { DatagramPacket dp = new DatagramPacket(msg, msg.length, lh, port); ds.send(dp); return null; }, acc); // Negative try { AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> { DatagramPacket dp = new DatagramPacket(msg, msg.length, lh, port); ds.send(dp); fail("Expected SecurityException"); return null; }, RESTRICTED_ACC); } catch (SecurityException expected) { } } }
80. SendSize#main()
Project: openjdk
File: SendSize.java
File: SendSize.java
public static void main(String[] args) throws Exception { DatagramSocket serverSocket = new DatagramSocket(); new ServerThread(serverSocket).start(); new ClientThread(serverSocket.getLocalPort()).start(); }
81. LocalSocketAddress#main()
Project: openjdk
File: LocalSocketAddress.java
File: LocalSocketAddress.java
public static void main(String[] args) throws SocketException { InetAddress IPv6LoopbackAddr = null; DatagramSocket soc = null; try { List<NetworkInterface> nics = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface nic : nics) { if (!nic.isLoopback()) continue; List<InetAddress> addrs = Collections.list(nic.getInetAddresses()); for (InetAddress addr : addrs) { if (addr instanceof Inet6Address) { IPv6LoopbackAddr = addr; break; } } } if (IPv6LoopbackAddr == null) { System.out.println("IPv6 is not available, exiting test."); return; } soc = new DatagramSocket(0, IPv6LoopbackAddr); if (!IPv6LoopbackAddr.equals(soc.getLocalAddress())) { throw new RuntimeException("Bound address is " + soc.getLocalAddress() + ", but should be " + IPv6LoopbackAddr); } } finally { if (soc != null) { soc.close(); } } }
82. BindFailTest#main()
Project: openjdk
File: BindFailTest.java
File: BindFailTest.java
public static void main(String args[]) throws Exception { DatagramSocket s = new DatagramSocket(); int port = s.getLocalPort(); for (int i = 0; i < 32000; i++) { try { DatagramSocket s2 = new DatagramSocket(port); } catch (BindException e) { } } }
83. HueEmulationUpnpServer#run()
Project: openhab2-addons
File: HueEmulationUpnpServer.java
File: HueEmulationUpnpServer.java
@Override public void run() { MulticastSocket recvSocket = null; // since jupnp shares port 1900, lets use a different port to send UDP packets on just to be safe. DatagramSocket sendSocket = null; byte[] buf = new byte[1000]; DatagramPacket recv = new DatagramPacket(buf, buf.length); while (running) { try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface ni = interfaces.nextElement(); Enumeration<InetAddress> addresses = ni.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress addr = addresses.nextElement(); if (addr instanceof Inet4Address && !addr.isLoopbackAddress()) { address = addr; break; } } } InetSocketAddress socketAddr = new InetSocketAddress(MULTI_ADDR, UPNP_PORT_RECV); recvSocket = new MulticastSocket(UPNP_PORT_RECV); recvSocket.joinGroup(socketAddr, NetworkInterface.getByInetAddress(address)); sendSocket = new DatagramSocket(); while (running) { recvSocket.receive(recv); if (recv.getLength() > 0) { String data = new String(recv.getData()); logger.trace("Got SSDP Discovery packet from " + recv.getAddress().getHostAddress() + ":" + recv.getPort()); if (data.startsWith("M-SEARCH")) { String msg = String.format(discoString, "http://" + address.getHostAddress().toString() + ":" + System.getProperty("org.osgi.service.http.port") + discoPath, usn); DatagramPacket response = new DatagramPacket(msg.getBytes(), msg.length(), recv.getAddress(), recv.getPort()); try { logger.trace("Sending to " + recv.getAddress().getHostAddress() + " : " + msg); sendSocket.send(response); } catch (IOException e) { logger.error("Could not send UPNP response", e); } } } } } catch (SocketException e) { logger.error("Socket error with UPNP server", e); } catch (IOException e) { logger.error("IO Error with UPNP server", e); } finally { IOUtils.closeQuietly(recvSocket); IOUtils.closeQuietly(sendSocket); if (running) { try { Thread.sleep(3000); } catch (InterruptedException e) { } } } } }
84. MaxCubeBridgeDiscovery#sendDiscoveryMessage()
Project: openhab2-addons
File: MaxCubeBridgeDiscovery.java
File: MaxCubeBridgeDiscovery.java
/** * Send broadcast message over all active interfaces * * @param discoverString * String to be used for the discovery */ private void sendDiscoveryMessage(String discoverString) { DatagramSocket bcSend = null; // Find the MaxCube using UDP broadcast try { bcSend = new DatagramSocket(); bcSend.setBroadcast(true); byte[] sendData = discoverString.getBytes(); // Broadcast the message over all the network interfaces Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); if (networkInterface.isLoopback() || !networkInterface.isUp()) { continue; } for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) { InetAddress[] broadcast = new InetAddress[3]; broadcast[0] = InetAddress.getByName("224.0.0.1"); broadcast[1] = InetAddress.getByName("255.255.255.255"); broadcast[2] = interfaceAddress.getBroadcast(); for (InetAddress bc : broadcast) { // Send the broadcast package! if (bc != null) { try { DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, bc, 23272); bcSend.send(sendPacket); } catch (IOException e) { logger.debug("IO error during MAX! Cube discovery: {}", e.getMessage()); } catch (Exception e) { logger.info(e.getMessage(), e); } logger.trace("Request packet sent to: {} Interface: {}", bc.getHostAddress(), networkInterface.getDisplayName()); } } } } logger.trace("Done looping over all network interfaces. Now waiting for a reply!"); } catch (IOException e) { logger.debug("IO error during MAX! Cube discovery: {}", e.getMessage()); } finally { try { if (bcSend != null) { bcSend.close(); } } catch (Exception e) { } } }
85. MaxCubeBridgeDiscovery#receiveDiscoveryMessage()
Project: openhab2-addons
File: MaxCubeBridgeDiscovery.java
File: MaxCubeBridgeDiscovery.java
private void receiveDiscoveryMessage() { DatagramSocket bcReceipt = null; try { discoveryRunning = true; bcReceipt = new DatagramSocket(23272); bcReceipt.setReuseAddress(true); bcReceipt.setSoTimeout(5000); while (discoveryRunning) { // Wait for a response byte[] recvBuf = new byte[1500]; DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length); bcReceipt.receive(receivePacket); // We have a response byte[] messageBuf = Arrays.copyOfRange(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getOffset() + receivePacket.getLength()); String message = new String(messageBuf); logger.trace("Broadcast response from {} : {} '{}'", receivePacket.getAddress(), message.length(), message); // Check if the message is correct if (message.startsWith("eQ3Max") && !message.equals(MAXCUBE_DISCOVER_STRING)) { String maxCubeIP = receivePacket.getAddress().getHostAddress(); String maxCubeState = message.substring(0, 8); String serialNumber = message.substring(8, 18); String msgValidid = message.substring(18, 19); String requestType = message.substring(19, 20); String rfAddress = ""; logger.debug("MAX! Cube found on network"); logger.debug("Found at : {}", maxCubeIP); logger.trace("Cube State: {}", maxCubeState); logger.debug("Serial : {}", serialNumber); logger.trace("Msg Valid : {}", msgValidid); logger.trace("Msg Type : {}", requestType); if (requestType.equals("I")) { rfAddress = Utils.getHex(Arrays.copyOfRange(messageBuf, 21, 24)).replace(" ", "").toLowerCase(); String firmwareVersion = Utils.getHex(Arrays.copyOfRange(messageBuf, 24, 26)).replace(" ", "."); logger.debug("RF Address: {}", rfAddress); logger.debug("Firmware : {}", firmwareVersion); } discoveryResultSubmission(maxCubeIP, serialNumber, rfAddress); } } } catch (SocketTimeoutException e) { logger.trace("No further response"); discoveryRunning = false; } catch (IOException e) { logger.debug("IO error during MAX! Cube discovery: {}", e.getMessage()); discoveryRunning = false; } finally { // Close the port! try { if (bcReceipt != null) { bcReceipt.close(); } } catch (Exception e) { logger.debug(e.toString()); } } }
86. UdpCubeCommand#sendUdpCommand()
Project: openhab2-addons
File: UdpCubeCommand.java
File: UdpCubeCommand.java
/** * Send broadcast message over all active interfaces * * @param commandString string to be used for the discovery * @param ipAddress IP address of the MAX! Cube * */ private void sendUdpCommand(String commandString, String ipAddress) { DatagramSocket bcSend = null; try { bcSend = new DatagramSocket(); bcSend.setBroadcast(true); byte[] sendData = commandString.getBytes(); // Broadcast the message over all the network interfaces Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); if (networkInterface.isLoopback() || !networkInterface.isUp()) { continue; } for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) { InetAddress[] broadcast = new InetAddress[3]; if (ipAddress != null && !ipAddress.isEmpty()) { broadcast[0] = InetAddress.getByName(ipAddress); } else { broadcast[0] = InetAddress.getByName("224.0.0.1"); broadcast[1] = InetAddress.getByName("255.255.255.255"); broadcast[2] = interfaceAddress.getBroadcast(); } for (InetAddress bc : broadcast) { // Send the broadcast package! if (bc != null) { try { DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, bc, 23272); bcSend.send(sendPacket); } catch (IOException e) { logger.debug("IO error during MAX! Cube UDP command sending: {}", e.getMessage()); } catch (Exception e) { logger.info(e.getMessage(), e); } logger.trace("Request packet sent to: {} Interface: {}", bc.getHostAddress(), networkInterface.getDisplayName()); } } } } logger.trace("Done looping over all network interfaces. Now waiting for a reply!"); } catch (IOException e) { logger.debug("IO error during MAX! Cube UDP command sending: {}", e.getMessage()); } finally { try { if (bcSend != null) { bcSend.close(); } } catch (Exception e) { } } }
87. UdpCubeCommand#receiveUdpCommandResponse()
Project: openhab2-addons
File: UdpCubeCommand.java
File: UdpCubeCommand.java
private void receiveUdpCommandResponse() { DatagramSocket bcReceipt = null; try { commandRunning = true; bcReceipt = new DatagramSocket(23272); bcReceipt.setReuseAddress(true); bcReceipt.setSoTimeout(5000); while (commandRunning) { // Wait for a response byte[] recvBuf = new byte[1500]; DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length); bcReceipt.receive(receivePacket); // We have a response String message = new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength()); logger.trace("Broadcast response from {} : {} '{}'", receivePacket.getAddress(), message.length(), message); // Check if the message is correct if (message.startsWith("eQ3Max") && !message.equals(MAXCUBE_COMMAND_STRING)) { commandResponse.put("maxCubeIP", receivePacket.getAddress().getHostAddress().toString()); commandResponse.put("maxCubeState", message.substring(0, 8)); commandResponse.put("serialNumber", message.substring(8, 18)); commandResponse.put("msgValidid", message.substring(18, 19)); String requestType = message.substring(19, 20); commandResponse.put("requestType", requestType); if (requestType.equals("I")) { commandResponse.put("rfAddress", Utils.getHex(message.substring(21, 24).getBytes()).replace(" ", "").toLowerCase()); commandResponse.put("firmwareVersion", Utils.getHex(message.substring(24, 26).getBytes()).replace(" ", ".")); } else { // TODO: Further parsing of the other message types commandResponse.put("messageResponse", Utils.getHex(message.substring(24).getBytes())); } commandRunning = false; logger.debug("MAX! UDP response"); for (String key : commandResponse.keySet()) { logger.debug("{}:{}{}", key, Strings.repeat(" ", 25 - key.length()), commandResponse.get(key)); } } } } catch (SocketTimeoutException e) { logger.trace("No further response"); commandRunning = false; } catch (IOException e) { logger.debug("IO error during MAX! Cube response: {}", e.getMessage()); commandRunning = false; } finally { // Close the port! try { if (bcReceipt != null) { bcReceipt.close(); } } catch (Exception e) { logger.debug(e.toString()); } } }
88. HarmonyHubDiscovery#sendDiscoveryMessage()
Project: openhab2-addons
File: HarmonyHubDiscovery.java
File: HarmonyHubDiscovery.java
/** * Send broadcast message over all active interfaces * * @param discoverString * String to be used for the discovery */ private void sendDiscoveryMessage(String discoverString) { DatagramSocket bcSend = null; try { bcSend = new DatagramSocket(); bcSend.setBroadcast(true); byte[] sendData = discoverString.getBytes(); // Broadcast the message over all the network interfaces Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); if (networkInterface.isLoopback() || !networkInterface.isUp()) { continue; } for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) { InetAddress[] broadcast = new InetAddress[3]; broadcast[0] = InetAddress.getByName("224.0.0.1"); broadcast[1] = InetAddress.getByName("255.255.255.255"); broadcast[2] = interfaceAddress.getBroadcast(); for (InetAddress bc : broadcast) { // Send the broadcast package! if (bc != null) { try { DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, bc, DISCO_PORT); bcSend.send(sendPacket); } catch (IOException e) { logger.error("IO error during HarmonyHub discovery: {}", e.getMessage()); } catch (Exception e) { logger.error(e.getMessage(), e); } logger.trace("Request packet sent to: {} Interface: {}", bc.getHostAddress(), networkInterface.getDisplayName()); } } } } } catch (IOException e) { logger.debug("IO error during HarmonyHub discovery: {}", e.getMessage()); } finally { try { if (bcSend != null) { bcSend.close(); } } catch (Exception e) { } } }
89. PifaceBinding#sendCommand()
Project: openhab
File: PifaceBinding.java
File: PifaceBinding.java
private byte sendCommand(PifaceNode node, byte command, byte commandAck, int pinNumber, int pinValue, int attempt) throws ErrorResponseException { logger.debug("Sending command (" + command + ") to " + node.host + ":" + node.listenerPort + " for pin " + pinNumber + " (value=" + pinValue + ")"); logger.debug("Attempt " + attempt + "..."); DatagramSocket socket = null; try { socket = new DatagramSocket(); socket.setSoTimeout(node.socketTimeout); InetAddress inetAddress = InetAddress.getByName(node.host); // send the packet byte[] sendData = new byte[] { command, (byte) pinNumber, (byte) pinValue }; DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, inetAddress, node.listenerPort); socket.send(sendPacket); // read the response byte[] receiveData = new byte[16]; DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); socket.receive(receivePacket); // check the response is valid if (receiveData[0] == PifaceCommand.ERROR_ACK.toByte()) { String msg = "Error 'ack' received"; logger.error(msg); throw new ErrorResponseException(msg); } if (receiveData[0] != commandAck) { String msg = "Unexpected 'ack' code received - expecting " + commandAck + " but got " + receiveData[0]; logger.error(msg); throw new ErrorResponseException(msg); } if (receiveData[1] != pinNumber) { String msg = "Invalid pin received - expecting " + pinNumber + " but got " + receiveData[1]; logger.error(msg); throw new ErrorResponseException(msg); } // return the data value logger.debug("Command successfully sent and acknowledged (returned " + receiveData[2] + ")"); return receiveData[2]; } catch (IOException e) { String msg = "Failed to send command (" + command + ") to " + node.host + ":" + node.listenerPort + " (attempt " + attempt + ")"; logger.error(msg, e); throw new ErrorResponseException(msg); } finally { if (socket != null) { socket.close(); } } }
90. NioUdpServerFilterEventTest#generate_all_kind_of_server_event()
Project: mina
File: NioUdpServerFilterEventTest.java
File: NioUdpServerFilterEventTest.java
@Test public void generate_all_kind_of_server_event() throws IOException, InterruptedException { final NioUdpServer server = new NioUdpServer(); server.getSessionConfig().setIdleTimeInMillis(IdleStatus.READ_IDLE, 2000); server.setFilters(new MyCodec(), new Handler()); server.bind(0); // warm up // Thread.sleep(100); final int port = server.getDatagramChannel().socket().getLocalPort(); final DatagramSocket[] clients = new DatagramSocket[CLIENT_COUNT]; InetSocketAddress serverAddy = new InetSocketAddress("127.0.0.1", port); // connect some clients for (int i = 0; i < CLIENT_COUNT; i++) { try { clients[i] = new DatagramSocket(); } catch (Exception e) { e.printStackTrace(); System.out.println("Creation client " + i + " failed"); } } // write some messages for (int i = 0; i < CLIENT_COUNT; i++) { byte[] data = ("test:" + i).getBytes(); clients[i].send(new DatagramPacket(data, data.length, serverAddy)); } // does the session open message was fired ? assertTrue(openLatch.await(WAIT_TIME, TimeUnit.MILLISECONDS)); // test is message was received by the server assertTrue(msgReadLatch.await(WAIT_TIME, TimeUnit.MILLISECONDS)); // does response was wrote and sent ? assertTrue(msgSentLatch.await(WAIT_TIME, TimeUnit.MILLISECONDS)); // read the echos final byte[] buffer = new byte[1024]; for (int i = 0; i < CLIENT_COUNT; i++) { DatagramPacket dp = new DatagramPacket(buffer, buffer.length); clients[i].receive(dp); final String text = new String(buffer, 0, dp.getLength()); assertEquals("test:" + i, text); } msgReadLatch = new CountDownLatch(CLIENT_COUNT); // write some messages again for (int i = 0; i < CLIENT_COUNT; i++) { byte[] data = ("test:" + i).getBytes(); clients[i].send(new DatagramPacket(data, data.length, serverAddy)); } // test is message was received by the server assertTrue(msgReadLatch.await(WAIT_TIME, TimeUnit.MILLISECONDS)); // close the session for (int i = 0; i < CLIENT_COUNT; i++) { clients[i].close(); } server.unbind(); }
91. BioUdpServerFilterEventTest#generate_all_kind_of_server_event()
Project: mina
File: BioUdpServerFilterEventTest.java
File: BioUdpServerFilterEventTest.java
@Test public void generate_all_kind_of_server_event() throws IOException, InterruptedException { final BioUdpServer server = new BioUdpServer(); server.getSessionConfig().setIdleTimeInMillis(IdleStatus.READ_IDLE, 2000); server.setFilters(new MyCodec(), new Handler()); server.bind(0); // warm up Thread.sleep(100); long t0 = System.currentTimeMillis(); final int port = server.getDatagramChannel().socket().getLocalPort(); System.err.println("port : " + port); final DatagramSocket[] clients = new DatagramSocket[CLIENT_COUNT]; InetSocketAddress serverAddy = new InetSocketAddress("127.0.0.1", port); // connect some clients for (int i = 0; i < CLIENT_COUNT; i++) { try { clients[i] = new DatagramSocket(); } catch (Exception e) { e.printStackTrace(); System.out.println("Creation client " + i + " failed"); } } // write some messages for (int i = 0; i < CLIENT_COUNT; i++) { byte[] data = ("test:" + i).getBytes(); clients[i].send(new DatagramPacket(data, data.length, serverAddy)); } // does the session open message was fired ? assertTrue(openLatch.await(WAIT_TIME, TimeUnit.MILLISECONDS)); // test is message was received by the server assertTrue(msgReadLatch.await(WAIT_TIME, TimeUnit.MILLISECONDS)); // does response was wrote and sent ? assertTrue(msgSentLatch.await(WAIT_TIME, TimeUnit.MILLISECONDS)); // read the echos final byte[] buffer = new byte[1024]; for (int i = 0; i < CLIENT_COUNT; i++) { DatagramPacket dp = new DatagramPacket(buffer, buffer.length); clients[i].receive(dp); final String text = new String(buffer, 0, dp.getLength()); assertEquals("test:" + i, text); } msgReadLatch = new CountDownLatch(CLIENT_COUNT); // write some messages again for (int i = 0; i < CLIENT_COUNT; i++) { byte[] data = ("test:" + i).getBytes(); clients[i].send(new DatagramPacket(data, data.length, serverAddy)); } // test is message was received by the server assertTrue(msgReadLatch.await(WAIT_TIME, TimeUnit.MILLISECONDS)); // wait echo // close the session assertEquals(CLIENT_COUNT, closedLatch.getCount()); for (int i = 0; i < CLIENT_COUNT; i++) { clients[i].close(); } // does the session close event was fired ? assertTrue(closedLatch.await(WAIT_TIME, TimeUnit.MILLISECONDS)); long t1 = System.currentTimeMillis(); System.out.println("Delta = " + (t1 - t0)); server.unbind(); }
92. BioUdpBenchmarkClient#start()
Project: mina
File: BioUdpBenchmarkClient.java
File: BioUdpBenchmarkClient.java
/** * {@inheritDoc} */ public void start(int port, final CountDownLatch counter, final byte[] data) throws IOException { InetAddress serverAddress = InetAddress.getLocalHost(); byte[] buffer = new byte[65507]; sender = new DatagramSocket(port + 1); DatagramPacket pduSent = new DatagramPacket(data, data.length, serverAddress, port); DatagramPacket pduReceived = new DatagramPacket(buffer, data.length); sender.send(pduSent); boolean done = false; while (!done) { try { sender.receive(pduReceived); for (int i = 0; i < pduReceived.getLength(); ++i) { counter.countDown(); if (counter.getCount() > 0) { sender.send(pduSent); break; } else { done = true; } } } catch (IOException ioe) { } } sender.close(); }
93. SyslogAppenderTest#setUp()
Project: log4j
File: SyslogAppenderTest.java
File: SyslogAppenderTest.java
protected void setUp() throws Exception { ds = new DatagramSocket(); ds.setSoTimeout(2000); }
94. Client#discoverHosts()
Project: kryonet
File: Client.java
File: Client.java
/** Broadcasts a UDP message on the LAN to discover any running servers. * @param udpPort The UDP port of the server. * @param timeoutMillis The number of milliseconds to wait for a response. */ public List<InetAddress> discoverHosts(int udpPort, int timeoutMillis) { List<InetAddress> hosts = new ArrayList<InetAddress>(); DatagramSocket socket = null; try { socket = new DatagramSocket(); broadcast(udpPort, socket); socket.setSoTimeout(timeoutMillis); while (true) { DatagramPacket packet = discoveryHandler.onRequestNewDatagramPacket(); try { socket.receive(packet); } catch (SocketTimeoutException ex) { if (INFO) info("kryonet", "Host discovery timed out."); return hosts; } if (INFO) info("kryonet", "Discovered server: " + packet.getAddress()); discoveryHandler.onDiscoveredHost(packet, getKryo()); hosts.add(packet.getAddress()); } } catch (IOException ex) { if (ERROR) error("kryonet", "Host discovery failed.", ex); return hosts; } finally { if (socket != null) socket.close(); discoveryHandler.onFinally(); } }
95. RConThreadBase#closeAllSockets_do()
Project: Kingdoms
File: RConThreadBase.java
File: RConThreadBase.java
/** * Closes all of the opened sockets */ protected void closeAllSockets_do(boolean logWarning) { int i = 0; for (DatagramSocket datagramsocket : this.socketList) { if (this.closeSocket(datagramsocket, false)) { ++i; } } this.socketList.clear(); for (ServerSocket serversocket : this.serverSocketList) { if (this.closeServerSocket_do(serversocket, false)) { ++i; } } this.serverSocketList.clear(); if (logWarning && 0 < i) { this.logWarning("Force closed " + i + " sockets"); } }
96. RandomPortNumberGenerator#isPortAvailable()
Project: jongo
File: RandomPortNumberGenerator.java
File: RandomPortNumberGenerator.java
/** * Test whether a port number is available (i.e. not bound). * * @return a random port number between {@code min} inclusively and * {@code max} exclusively */ public static boolean isPortAvailable(int port) { ServerSocket ss = null; DatagramSocket ds = null; try { ss = new ServerSocket(port); ss.setReuseAddress(true); ds = new DatagramSocket(port); ds.setReuseAddress(true); } catch (IOException e) { return false; } finally { if (ds != null) { ds.close(); } if (ss != null) { try { ss.close(); } catch (IOException e) { } } } try { new Socket("localhost", port); } catch (UnknownHostException e) { return false; } catch (IOException e) { return true; } return false; }
97. SendSize#main()
Project: jdk7u-jdk
File: SendSize.java
File: SendSize.java
public static void main(String[] args) throws Exception { DatagramSocket serverSocket = new DatagramSocket(); new ServerThread(serverSocket).start(); new ClientThread(serverSocket.getLocalPort()).start(); }
98. LocalSocketAddress#main()
Project: jdk7u-jdk
File: LocalSocketAddress.java
File: LocalSocketAddress.java
public static void main(String[] args) throws SocketException { InetAddress IPv6LoopbackAddr = null; DatagramSocket soc = null; try { List<NetworkInterface> nics = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface nic : nics) { if (!nic.isLoopback()) continue; List<InetAddress> addrs = Collections.list(nic.getInetAddresses()); for (InetAddress addr : addrs) { if (addr instanceof Inet6Address) { IPv6LoopbackAddr = addr; break; } } } if (IPv6LoopbackAddr == null) { System.out.println("IPv6 is not available, exiting test."); return; } soc = new DatagramSocket(0, IPv6LoopbackAddr); if (!IPv6LoopbackAddr.equals(soc.getLocalAddress())) { throw new RuntimeException("Bound address is " + soc.getLocalAddress() + ", but should be " + IPv6LoopbackAddr); } } finally { if (soc != null) { soc.close(); } } }
99. BindFailTest#main()
Project: jdk7u-jdk
File: BindFailTest.java
File: BindFailTest.java
public static void main(String args[]) throws Exception { DatagramSocket s = new DatagramSocket(); int port = s.getLocalPort(); for (int i = 0; i < 32000; i++) { try { DatagramSocket s2 = new DatagramSocket(port); } catch (BindException e) { } } }
100. NettyServerBase#available()
Project: incubator-tajo
File: NettyServerBase.java
File: NettyServerBase.java
private static boolean available(int port) throws IOException { if (port < 1024 || port > 65535) { throw new IllegalArgumentException("Port Number Out of Bound: " + 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) { return false; } finally { if (ss != null) { ss.close(); } if (ds != null) { ds.close(); } } }