List of usage examples for java.net DatagramSocket DatagramSocket
public DatagramSocket() throws SocketException
From source file:UDPOutputStream.java
/************ opening and closing the stream ************/ /*/*from www . j a v a2 s . co m*/ ***************************************************************** *** *** *** Name : open *** *** By : U. Bergstrom (Creare Inc., Hanover, NH) *** *** For : E-Scan *** *** Date : October, 2001 *** *** *** *** Copyright 2001 Creare Inc. *** *** All Rights Reserved *** *** *** *** Description : *** *** The user may use this method to set the address and *** *** port of the UDP socket to write to. *** *** *** ***************************************************************** */ public void open(InetAddress address, int portI) throws SocketException, IOException { dsock = new DatagramSocket(); iAdd = address; port = portI; }
From source file:org.cc86.MMC.client.Main.java
public static String serverDiscovery() { String res = "0.0.0.0"; DatagramSocket c;//from w w w.j a va 2s .c o m // Find the server using UDP broadcast try { //Open a random port to send the package c = new DatagramSocket(); c.setBroadcast(true); byte[] sendData = "DISCOVER_MMC_REQUEST".getBytes(); //Try the 255.255.255.255 first try { DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName("255.255.255.255"), 0xCC86); c.send(sendPacket); l.info("Request packet sent to: 255.255.255.255 (DEFAULT)"); } catch (Exception e) { } // Broadcast the message over all the network interfaces Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = (NetworkInterface) interfaces.nextElement(); if (networkInterface.isLoopback() || !networkInterface.isUp()) { continue; // Don't want to broadcast to the loopback interface } for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) { InetAddress broadcast = interfaceAddress.getBroadcast(); if (broadcast == null) { continue; } // Send the broadcast package! try { DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 8888); c.send(sendPacket); } catch (Exception e) { } l.info("Request packet sent to: " + broadcast.getHostAddress() + "; Interface: " + networkInterface.getDisplayName()); } } l.info("Done looping over all network interfaces. Now waiting for a reply!"); //Wait for a response byte[] recvBuf = new byte[15000]; DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length); c.receive(receivePacket); //We have a response l.info("Broadcast response from server: " + receivePacket.getAddress().getHostAddress()); //Check if the message is correct String message = new String(receivePacket.getData()).trim(); if (message.equals("DISCOVER_MMC_RESPONSE")) { //DO SOMETHING WITH THE SERVER'S IP (for example, store it in your controller) res = (receivePacket.getAddress() + "").substring(1); } //Close the port! c.close(); } catch (IOException ex) { } return res; }
From source file:org.springframework.integration.ip.udp.DatagramPacketSendingHandlerTests.java
@Test @Ignore/* w w w. ja v a2 s.c o m*/ public void verifySendMulticastWithAcks() throws Exception { final List<Integer> openPorts = SocketUtils.findAvailableUdpSockets(SocketUtils.getRandomSeedPort(), 2); final int testPort = openPorts.get(0); final int ackPort = openPorts.get(1); final String multicastAddress = "225.6.7.8"; final String payload = "foobar"; final CountDownLatch latch1 = new CountDownLatch(2); final CountDownLatch latch2 = new CountDownLatch(2); Runnable catcher = new Runnable() { public void run() { try { byte[] buffer = new byte[1000]; DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length); MulticastSocket socket = new MulticastSocket(testPort); InetAddress group = InetAddress.getByName(multicastAddress); socket.joinGroup(group); latch1.countDown(); LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " waiting for packet"); socket.receive(receivedPacket); socket.close(); byte[] src = receivedPacket.getData(); int length = receivedPacket.getLength(); int offset = receivedPacket.getOffset(); byte[] dest = new byte[6]; System.arraycopy(src, offset + length - 6, dest, 0, 6); assertEquals(payload, new String(dest)); LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " received packet"); DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper(); mapper.setAcknowledge(true); mapper.setLengthCheck(true); Message<byte[]> message = mapper.toMessage(receivedPacket); Object id = message.getHeaders().get(IpHeaders.ACK_ID); byte[] ack = id.toString().getBytes(); DatagramPacket ackPack = new DatagramPacket(ack, ack.length, new InetSocketAddress("localHost", ackPort)); DatagramSocket out = new DatagramSocket(); out.send(ackPack); out.close(); latch2.countDown(); } catch (Exception e) { noMulticast = true; latch1.countDown(); e.printStackTrace(); } } }; Executor executor = Executors.newFixedThreadPool(2); executor.execute(catcher); executor.execute(catcher); latch1.await(3000, TimeUnit.MILLISECONDS); if (noMulticast) { return; } MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(multicastAddress, testPort, true, true, "localhost", ackPort, 500000); handler.setMinAcksForSuccess(2); handler.handleMessage(MessageBuilder.withPayload(payload).build()); assertTrue(latch2.await(10000, TimeUnit.MILLISECONDS)); handler.shutDown(); }
From source file:org.graylog2.inputs.transports.UdpTransportTest.java
private void sendUdpDatagram(String hostname, int port, int size) throws IOException { final InetAddress address = InetAddress.getByName(hostname); final byte[] data = new byte[size]; final DatagramPacket packet = new DatagramPacket(data, data.length, address, port); DatagramSocket toSocket = null; try {//from www .j a va 2 s.com toSocket = new DatagramSocket(); toSocket.send(packet); } finally { if (toSocket != null) { toSocket.close(); } } }
From source file:com.webobjects.monitor.application.HostsPage.java
private boolean hostMeetsMinimumVersion(InetAddress anAddress) { byte[] versionRequest; try {// w w w. jav a2 s. c o m versionRequest = ("womp://queryVersion").getBytes(CharEncoding.UTF_8); } catch (UnsupportedEncodingException uee) { versionRequest = ("womp://queryVersion").getBytes(); } DatagramPacket outgoingPacket = new DatagramPacket(versionRequest, versionRequest.length, anAddress, WOApplication.application().lifebeatDestinationPort()); byte[] mbuffer = new byte[1000]; DatagramPacket incomingPacket = new DatagramPacket(mbuffer, mbuffer.length); DatagramSocket socket = null; try { socket = new DatagramSocket(); socket.send(outgoingPacket); incomingPacket.setLength(mbuffer.length); socket.setSoTimeout(2000); socket.receive(incomingPacket); String reply = new String(incomingPacket.getData()); if (reply.startsWith("womp://replyVersion/")) { int lastIndex = reply.lastIndexOf(":webObjects"); lastIndex += 11; String version = reply.substring(lastIndex); if (version.equals("4.5")) { return false; } } else { return false; } } catch (InterruptedIOException iioe) { return true; } catch (SocketException se) { return true; } catch (Throwable e) { return false; } finally { if (socket != null) { socket.close(); } } return true; }
From source file:org.opennms.netmgt.syslogd.SyslogdLoadIT.java
public void doTestSyslogReceiver() throws Exception { final int eventCount = 100; List<Integer> foos = new ArrayList<Integer>(); for (int i = 0; i < eventCount; i++) { int eventNum = Double.valueOf(Math.random() * 10000).intValue(); foos.add(eventNum);/*from www. j av a2s . c o m*/ } m_eventCounter.setAnticipated(eventCount); String testPduFormat = "2010-08-19 localhost foo%d: load test %d on tty1"; SyslogClient sc = new SyslogClient(null, 10, SyslogClient.LOG_USER, addr("127.0.0.1")); // Test by sending over a java.net socket final DatagramSocket socket = new DatagramSocket(); System.err.println("Starting to send packets"); final long start = System.currentTimeMillis(); for (int i = 0; i < eventCount; i++) { int foo = foos.get(i); DatagramPacket pkt = sc.getPacket(SyslogClient.LOG_DEBUG, String.format(testPduFormat, foo, foo)); socket.send(pkt); } socket.close(); /* // Test by sending over an NIO channel SocketAddress address = new InetSocketAddress(InetAddressUtils.getLocalHostAddress(), SyslogClient.PORT); final DatagramChannel channel = DatagramChannel.open(); final ByteBuffer buffer = ByteBuffer.allocate(SyslogReceiverNioThreadPoolImpl.MAX_PACKET_SIZE); buffer.clear(); System.err.println("Starting to send packets"); final long start = System.currentTimeMillis(); for (int i = 0; i < eventCount; i++) { int foo = foos.get(i); buffer.put(SyslogClient.getPacketPayload(SyslogClient.LOG_USER, null, SyslogClient.LOG_DEBUG, String.format(testPduFormat, foo, foo))); buffer.flip(); channel.send(buffer, address); buffer.clear(); } channel.close(); */ long mid = System.currentTimeMillis(); System.err.println(String.format("Sent %d packets in %d milliseconds", eventCount, mid - start)); m_eventCounter.waitForFinish(30000); long end = System.currentTimeMillis(); System.err.println( String.format("Events expected: %d, events received: %d", eventCount, m_eventCounter.getCount())); final long total = (end - start); final double eventsPerSecond = (eventCount * 1000.0 / total); System.err.println(String.format("total time: %d, wait time: %d, events per second: %8.4f", total, (end - mid), eventsPerSecond)); assertEquals(eventCount, m_eventCounter.getCount()); }
From source file:energy.usef.core.util.DateTimeUtil.java
private static synchronized String getUDPInfo(String message) { try {/*from w ww . j av a 2 s. co m*/ LOGGER.debug("SENDING: {}", message); byte[] buf = message.getBytes(); InetAddress address = InetAddress.getByName(serverIp); DatagramSocket socket = new DatagramSocket(); socket.send(new DatagramPacket(buf, buf.length, address, port)); DatagramPacket result = new DatagramPacket(new byte[PACKAGE_BUFFER], PACKAGE_BUFFER); socket.disconnect(); socket.setSoTimeout(RESPONSE_TIMEOUT); socket.receive(result); socket.disconnect(); socket.close(); String resultStr = new String(result.getData()).trim(); LOGGER.debug("RECEIVED: {} ", resultStr); errorCount = 0; return resultStr; } catch (IOException e) { LOGGER.error(e.getMessage(), e); errorCount++; if (errorCount >= MAX_ERROR_COUNT) { LOGGER.error("Unable to run simulation correctly."); System.exit(1); } } return null; }
From source file:lockstep.LockstepServer.java
/** * Implements the handshake protocol server side, setting up the UDP * connection, queues and threads for a specific client. * To be run in parallel threads, one for each client, as they need * to synchronize to correctly setup the lockstep protocol. * It signals success through a latch or failure through interruption to the * server thread./*from w w w .j a va 2 s .com*/ * * @param tcpSocket Connection with the client, to be used in handshake only * @param firstFrameNumber Frame number to initialize the lockstep protocol * @param barrier Used for synchronization with concurrent handshake sessions * @param latch Used to signal the successful completion of the handshake session. * @param server Used to signal failure of the handshake sessions, via interruption. */ private void serverHandshakeProtocol(Socket tcpSocket, int firstFrameNumber, CyclicBarrier barrier, CountDownLatch latch, LockstepServer server) { try (ObjectOutputStream oout = new ObjectOutputStream(tcpSocket.getOutputStream());) { oout.flush(); try (ObjectInputStream oin = new ObjectInputStream(tcpSocket.getInputStream());) { //Receive hello message from client and reply LOG.info("Waiting an hello from " + tcpSocket.getInetAddress().getHostAddress()); oout.flush(); ClientHello hello = (ClientHello) oin.readObject(); LOG.info("Received an hello from " + tcpSocket.getInetAddress().getHostAddress()); DatagramSocket udpSocket = new DatagramSocket(); openSockets.add(udpSocket); InetSocketAddress clientUDPAddress = new InetSocketAddress( tcpSocket.getInetAddress().getHostAddress(), hello.clientUDPPort); udpSocket.connect(clientUDPAddress); int assignedClientID; do { assignedClientID = (new Random()).nextInt(100000) + 10000; } while (!this.clientIDs.add(assignedClientID)); LOG.info("Assigned hostID " + assignedClientID + " to " + tcpSocket.getInetAddress().getHostAddress() + ", sending helloReply"); ServerHelloReply helloReply = new ServerHelloReply(udpSocket.getLocalPort(), assignedClientID, clientsNumber, firstFrameNumber); oout.writeObject(helloReply); ConcurrentHashMap<Integer, TransmissionQueue> clientTransmissionFrameQueues = new ConcurrentHashMap<>(); this.transmissionFrameQueueTree.put(assignedClientID, clientTransmissionFrameQueues); ACKSet clientAckQueue = new ACKSet(); ackQueues.put(assignedClientID, clientAckQueue); clientReceiveSetup(assignedClientID, udpSocket, firstFrameNumber, clientTransmissionFrameQueues); barrier.await(); //Send second reply ClientsAnnouncement announcement = new ClientsAnnouncement(); announcement.clientIDs = ArrayUtils.toPrimitive(this.clientIDs.toArray(new Integer[0])); oout.writeObject(announcement); clientTransmissionSetup(assignedClientID, firstFrameNumber, udpSocket, clientTransmissionFrameQueues); //Wait for other handshakes to reach final step barrier.await(); oout.writeObject(new SimulationStart()); //Continue with execution latch.countDown(); } } catch (IOException | ClassNotFoundException ioEx) { LOG.fatal("Exception at handshake with client"); LOG.fatal(ioEx); server.interrupt(); } catch (InterruptedException | BrokenBarrierException inEx) { //Interruptions come from failure in parallel handshake sessions, and signal termination } }
From source file:org.jini.commands.multicast.MulticastSender.java
private void startMulticastSender() throws NoSuchAlgorithmException { byte[] outBuf; // Interval in MiliSeconds final int INTERVAL = this.getInterval(); // Port //from w ww.ja v a 2 s. c o m final int PORT = this.getPort(); // Multicast Group String mcastGroup = this.getMulticastGroup(); String fl = this.getFile(); String fileName = this.getFile(); // Read Data from File String msg = this.getFileContents(fileName); // MD5 CheckSum String mdfiveSum = this.checkFileMD5(fileName); // Jini Logging JiniCommandsLogger jcl = new JiniCommandsLogger(); System.out.println("Started Multicast Sender. Sending Datagram every : " + INTERVAL + " Miliseconds"); if (logDatagramMessages == true) { System.out.println("Logging to Directory : " + jcl.getJiniLogDir()); } else { System.out.println("Logging not turned on, add -l to start logging. "); } System.out.println("'c + ENTER' or 'x + ENTER' to stop Multicast Sender."); PrintChar printChar = new PrintChar(); printChar.setOutPutChar(">"); try { Scanner in = new Scanner(System.in); printChar.start(); DatagramSocket socket = new DatagramSocket(); long counter = 0; while (this.running) { // Every 10th broadcast the file is checked if it has changed (MD5). // If it has the new data is read and broadcasted counter++; if (counter == 10) { if (mdfiveSum.equals(this.checkFileMD5(fileName)) == false) { msg = this.getFileContents(fileName); } counter = 0; } outBuf = msg.getBytes(); //Send to multicast IP address and port InetAddress address = InetAddress.getByName(mcastGroup); DatagramPacket outPacket = new DatagramPacket(outBuf, outBuf.length, address, PORT); socket.send(outPacket); if (logDatagramMessages == true) { jcl.writeLog(msg); } if ((in.nextLine().equalsIgnoreCase("c")) || (in.nextLine().equalsIgnoreCase("x"))) { this.running = false; } try { Thread.sleep(INTERVAL); } catch (InterruptedException ie) { printChar.setStopPrinting(true); this.setJcError(true); this.addErrorMessages("Error : An error occured in the Sleep thread."); } } } catch (IOException ioe) { printChar.setStopPrinting(true); /* DatagramPacket is just a wrapper on a UDP based socket, so the usual UDP rules apply. 64 kilobytes is the theoretical maximum size of a complete IP datagram, but only 576 bytes are guaranteed to be routed. On any given network path, the link with the smallest Maximum Transmit Unit will determine the actual limit. (1500 bytes, less headers is the common maximum, but it is impossible to predict how many headers there will be so its safest to limit messages to around 1400 bytes.) If you go over the MTU limit, IPv4 will automatically break the datagram up into fragments and reassemble them at the end, but only up to 64 kilobytes and only if all fragments make it through. If any fragment is lost, or if any device decides it doesn't like fragments, then the entire packet is lost. As noted above, it is impossible to know in advance what the MTU of path will be. There are various algorithms for experimenting to find out, but many devices do not properly implement (or deliberately ignore) the necessary standards so it all comes down to trial and error. Or you can just guess 1400 bytes per message. As for errors, if you try to send more bytes than the OS is configured to allow, you should get an EMSGSIZE error or its equivalent. If you send less than that but more than the network allows, the packet will just disappear. */ this.setJcError(true); this.addErrorMessages("Info : 64 kilobytes is the theoretical maximum size of a complete IP Datagram"); this.addErrorMessages("Error : " + ioe); } printChar.setStopPrinting(true); this.done = true; }
From source file:org.springframework.integration.syslog.inbound.SyslogReceivingChannelAdapterTests.java
@Test public void testUdpRFC5424() throws Exception { SyslogReceivingChannelAdapterFactoryBean factory = new SyslogReceivingChannelAdapterFactoryBean( SyslogReceivingChannelAdapterFactoryBean.Protocol.udp); int port = SocketUtils.findAvailableUdpSocket(1514); factory.setPort(port);/*from w w w . jav a 2 s . c o m*/ PollableChannel outputChannel = new QueueChannel(); factory.setOutputChannel(outputChannel); factory.setBeanFactory(mock(BeanFactory.class)); factory.setConverter(new RFC5424MessageConverter()); factory.afterPropertiesSet(); factory.start(); UdpSyslogReceivingChannelAdapter adapter = (UdpSyslogReceivingChannelAdapter) factory.getObject(); Thread.sleep(1000); byte[] buf = ("<14>1 2014-06-20T09:14:07+00:00 loggregator d0602076-b14a-4c55-852a-981e7afeed38 DEA - " + "[exampleSDID@32473 iut=\\\"3\\\" eventSource=\\\"Application\\\" eventID=\\\"1011\\\"]" + "[exampleSDID@32473 iut=\\\"3\\\" eventSource=\\\"Application\\\" eventID=\\\"1011\\\"] Removing instance") .getBytes("UTF-8"); DatagramPacket packet = new DatagramPacket(buf, buf.length, new InetSocketAddress("localhost", port)); DatagramSocket socket = new DatagramSocket(); socket.send(packet); socket.close(); @SuppressWarnings("unchecked") Message<Map<String, ?>> message = (Message<Map<String, ?>>) outputChannel.receive(10000); assertNotNull(message); assertEquals("loggregator", message.getPayload().get("syslog_HOST")); adapter.stop(); }