List of usage examples for java.net DatagramPacket DatagramPacket
public DatagramPacket(byte buf[], int length)
From source file:QuoteServerThread.java
public void run() { if (socket == null) return;/* w w w . ja v a 2 s . c om*/ while (moreQuotes) { try { byte[] buf = new byte[256]; DatagramPacket packet; InetAddress address; int port; String dString = null; // receive request packet = new DatagramPacket(buf, 256); socket.receive(packet); address = packet.getAddress(); port = packet.getPort(); // send response if (qfs == null) dString = new Date().toString(); else dString = getNextQuote(); buf = dString.getBytes(); packet = new DatagramPacket(buf, buf.length, address, port); socket.send(packet); } catch (IOException e) { System.err.println("IOException: " + e); moreQuotes = false; e.printStackTrace(); } } socket.close(); }
From source file:org.apache.jcs.auxiliary.lateral.socket.udp.LateralUDPReceiver.java
/** * Highly unreliable. If it is processing one message while another comes in * , the second message is lost. This is for low concurency peppering. *//* w w w . ja v a2 s . c o m*/ public Object waitForMessage() throws IOException { final DatagramPacket packet = new DatagramPacket(m_buffer, m_buffer.length); Object obj = null; try { m_socket.receive(packet); final ByteArrayInputStream byteStream = new ByteArrayInputStream(m_buffer, 0, packet.getLength()); final ObjectInputStream objectStream = new ObjectInputStream(byteStream); obj = objectStream.readObject(); } catch (Exception e) { log.error(e); //throw new CacheException( "Error receving multicast packet", e); } return obj; }
From source file:org.nebulaframework.discovery.multicast.MulticastDiscovery.java
/** * Starts Multicast Discovery Service. This can only * be invoked by a Nebula ClusterManager. * /*w w w . j a v a 2s .co m*/ * @throws IOException if occurred during operation * @throws UnsupportedOperationException if invoked by non-ClusterManager nodes. */ public static void startService() throws IOException, UnsupportedOperationException { // Only allowed for ClusterManagers if (!Grid.isClusterManager()) { throw new UnsupportedOperationException( "Multicast Discovery Service can be enabled only for ClusterManagers"); } // Start Service Thread t = new Thread(new Runnable() { public void run() { try { // Start Multicast Socket and listen for Requests final MulticastSocket mSock = new MulticastSocket(SERVICE_PORT); mSock.joinGroup(SERVICE_REQUEST_IP); // Infinite Loop while (true) { // Buffer (for Greeting Message) byte[] msg = new byte[GREET_MSG.getBytes("UTF-8").length]; // Create Datagram Packet DatagramPacket packet = new DatagramPacket(msg, msg.length); // Wait and Receive Request mSock.receive(packet); log.debug("[MulticastDiscovery] Received Discovery Request"); // Check if Greeting Message is valid try { String greet = new String(packet.getData()); if (!greet.equals(GREET_MSG)) { throw new IllegalArgumentException("Invalid Greeting"); } } catch (Exception e) { log.debug("Malformed Multicast Message Igonored"); continue; } // Respond doRespond(); } } catch (IOException e) { log.error("[MulticastDiscovery] Service Failed on Receive", e); } } }); t.setDaemon(true); // Run as Daemon thread t.start(); // Start Service log.debug("[MulticastDiscovery] Service Started"); }
From source file:org.eredlab.g4.ccl.net.CharGenUDPClient.java
/*** * The default CharGenUDPClient constructor. It initializes some internal * data structures for sending and receiving the necessary datagrams for * the chargen and related protocols./*w w w . ja va2 s . c o m*/ ***/ public CharGenUDPClient() { // CharGen return packets have a maximum length of 512 __receiveData = new byte[512]; __receivePacket = new DatagramPacket(__receiveData, 512); __sendPacket = new DatagramPacket(new byte[0], 0); }
From source file:org.springframework.integration.ip.udp.DatagramPacketSendingHandlerTests.java
@Test public void verifySendWithAck() throws Exception { final List<Integer> openPorts = SocketUtils.findAvailableUdpSockets(SocketUtils.getRandomSeedPort(), 2); final int testPort = openPorts.get(0); final int ackPort = openPorts.get(1); byte[] buffer = new byte[1000]; final DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length); final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); UnicastSendingMessageHandler handler = new UnicastSendingMessageHandler("localhost", testPort, true, true, "localhost", ackPort, 5000); handler.afterPropertiesSet();/*from ww w.jav a 2s. co m*/ Executors.newSingleThreadExecutor().execute(new Runnable() { public void run() { try { DatagramSocket socket = new DatagramSocket(testPort); latch1.countDown(); socket.receive(receivedPacket); socket.close(); DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper(); mapper.setAcknowledge(true); mapper.setLengthCheck(true); Message<byte[]> message = mapper.toMessage(receivedPacket); Object id = message.getHeaders().get(IpHeaders.ACK_ID); byte[] ack = id.toString().getBytes(); DatagramPacket ackPack = new DatagramPacket(ack, ack.length, new InetSocketAddress("localHost", ackPort)); DatagramSocket out = new DatagramSocket(); out.send(ackPack); out.close(); latch2.countDown(); } catch (Exception e) { e.printStackTrace(); } } }); latch1.await(3000, TimeUnit.MILLISECONDS); String payload = "foobar"; handler.handleMessage(MessageBuilder.withPayload(payload).build()); assertTrue(latch2.await(10000, TimeUnit.MILLISECONDS)); byte[] src = receivedPacket.getData(); int length = receivedPacket.getLength(); int offset = receivedPacket.getOffset(); byte[] dest = new byte[6]; System.arraycopy(src, offset + length - 6, dest, 0, 6); assertEquals(payload, new String(dest)); handler.shutDown(); }
From source file:org.squidy.manager.protocol.multicast.MulticastServer.java
@Override public void run() { while (running) { try {/*w ww.jav a2s . c om*/ byte[] buffer = new byte[BUFFER_SIZE]; DatagramPacket packet = new DatagramPacket(buffer, BUFFER_SIZE); socket.receive(packet); data = new String(packet.getData()); int last = 0; while (last < BUFFER_SIZE) { if (buffer[last] == 0) break; last++; } data = data.substring(0, last); if (last == BUFFER_SIZE) { LOG.error("Input buffer overflow"); } else { for (MulticastListener listener : listeners) { listener.parseData(data); } } for (MulticastListener listener : listeners) { listener.parseData(packet.getData()); } } catch (IOException e) { if (LOG.isErrorEnabled()) { LOG.error("Connection error occured."); } } } socket.close(); }
From source file:net.di2e.ddf.argo.probe.responder.ProbeHandler.java
@Override public void run() { LOGGER.debug("Listening for any multicast packets."); String data = ""; while (!isCanceled) { try {/*from w w w . j a va 2 s. c om*/ byte buf[] = new byte[1024]; DatagramPacket pack = new DatagramPacket(buf, buf.length); socket.receive(pack); data = new String(pack.getData(), pack.getOffset(), pack.getLength()); LOGGER.debug("Packet received with the following payload: {}.", data); Probe probe = JAXB.unmarshal(new StringReader(data), Probe.class); List<RespondTo> respondTo = probe.getRa().getRespondTo(); boolean ignoreProbe = false; if (ignoreProbesList != null && !ignoreProbesList.isEmpty()) { for (String ignoreProbeString : ignoreProbesList) { String updatedIgnoreString = expandRespondToAddress(ignoreProbeString); // TODO cache the request ID and use that instead of the local hostname if (StringUtils.equalsIgnoreCase(updatedIgnoreString, respondTo.get(0).getValue())) { LOGGER.debug( "Configuration is set to ignore probes that have a respondTo of '{}'. Incoming probe contains respondTo of '{}'. IGNORING PROBE.", ignoreProbeString, respondTo.get(0).getValue()); ignoreProbe = true; } } } if (!ignoreProbe) { List<String> contractIDs = probe.getScids().getServiceContractID(); // TODO handle the different contractID // URI contractId = probe.getContractID(); String probeId = probe.getId(); String response = generateServiceResponse(probe.getRespondToPayloadType(), contractIDs, probeId); if (StringUtils.isNotBlank(response)) { LOGGER.debug("Returning back to {} with the following response:\n{}", respondTo.get(0).getValue(), response); sendResponse(respondTo.get(0).getValue(), response, probe.getRespondToPayloadType()); } else { LOGGER.debug( "No services found that match the incoming contract IDs, not sending a response."); } } } catch (DataBindingException e) { LOGGER.warn("Issue parsing probe response: {}", data, e); } catch (SocketTimeoutException ste) { LOGGER.trace("Received timeout on socket, resetting socket to check for cancellation."); } catch (IOException ioe) { if (!isCanceled) { LOGGER.warn("Error while trying to receive a packet, shutting down listener", ioe); } break; } } if (isCanceled) { LOGGER.debug("Listener was canceled, not receiving any more multicast packets."); } }
From source file:net.sourceforge.vulcan.ant.receiver.UdpEventSource.java
@Override public void run() { final DatagramSocket socket = openSocket(); active = true;//from ww w .j a v a 2 s .co m synchronized (this) { notifyAll(); } final byte[] buffer = new byte[8192]; try { final DatagramPacket packet = new DatagramPacket(buffer, buffer.length); while (active) { try { socket.receive(packet); final AntEventSummary summary = deserialize(packet.getData()); fireEvent(summary); } catch (SocketTimeoutException e) { continue; } catch (Exception e) { handleException(e); } } } finally { socket.close(); } }
From source file:udpserver.UDPui.java
private void tempReceiveUDP() { background = new Runnable() { public void run() { try { serverSocket = new DatagramSocket(9876); } catch (SocketException ex) { Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex); }//from w ww . j a va2 s.co m // while (true) { // byte[] receiveData = new byte[1024]; // DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); // if (!new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength()).equals("")) { // int count = 1; while (true) { try { byte[] receiveData = new byte[total_byte]; byte[] sendData = new byte[32]; DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); String message = new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength()); // String word = serverSocket.getInetAddress().toString(); // Integer count = counting.get(word); // if (count == null) { // counting.put(word, 1); // } // else { // counting.put(word, count + 1); // } boolean looprun = true; String word = receivePacket.getAddress().getHostAddress(); System.out.println(word); // System.out.println(message); while (looprun) { if (message.contains("&")) { message = message.substring(message.indexOf("&") + 1); Integer count = counting.get(word); if (count == null) { counting.put(word, 2); } else { counting.put(word, count + 1); } // System.out.println(count + ":" + message); } else { looprun = false; } } if (message.equals("end")) { valuePane.setCaretPosition(valuePane.getDocument().getLength()); //send back to mobile InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); String capitalizedSentence = counting.get(word) + ""; sendData = capitalizedSentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); //end send back to mobile // count = 1; // break; counting.remove(word); } else if (available) { // series.add(count, Double.parseDouble(message)); // valuePane.setText(valuePane.getText().toString() + count + ":" + message + "\n"); // valuePane.setCaretPosition(valuePane.getDocument().getLength()); // count++; } } catch (IOException ex) { Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex); } } // } // } } }; backgroundProcess = new Thread(background); }
From source file:uk.co.propter.sleeponlan.SleepService.java
private DatagramPacket receivePacket() { DatagramPacket packet = new DatagramPacket(new byte[256], 256); try {//from ww w. ja v a2s . c o m socket.receive(packet); } catch (IOException e) { logger.warning("Received bad packet."); } return packet; }