List of usage examples for java.net DatagramPacket DatagramPacket
public DatagramPacket(byte buf[], int length)
From source file:org.openehealth.ipf.commons.ihe.core.atna.UdpServer.java
@Override public void run() { byte[] buffer = new byte[BUFFER_SIZE]; try {/*from w w w . j a v a2 s . com*/ socket = new DatagramSocket(port); LOG.debug("UDP server started on port " + port); } catch (SocketException e) { LOG.error("cannot open datagram socket", e); return; } try { while (true) { DatagramPacket packet = new DatagramPacket(buffer, buffer.length); socket.receive(packet); packets.add(packetToString(packet)); countDown(); } } catch (SocketException e) { LOG.debug("socket closed"); } catch (IOException e) { LOG.error(e); } }
From source file:org.proto.led.network.WiFiControllerService.java
private void listenAndWaitAndThrowIntent(InetAddress broadcastIP, Integer port) throws Exception { byte[] recvBuf = new byte[400]; if (socket == null || socket.isClosed()) { socket = new DatagramSocket(port); socket.setSoTimeout(5000);//from www .jav a 2 s . c o m socket.setBroadcast(true); } DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length); Log.i(TAG, "Waiting for UDP broadcast"); socket.receive(packet); String senderIP = packet.getAddress().getHostAddress(); parseMessage(recvBuf, senderIP); String message = new String(packet.getData()).trim(); Log.i(TAG, "Got UDP broadcast from " + senderIP + ", message: " + message); socket.close(); }
From source file:org.openhab.io.hueemulation.internal.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 {/*from w ww. jav a 2 s. c om*/ if (discoveryIp != null && discoveryIp.trim().length() > 0) { address = InetAddress.getByName(discoveryIp); } else { 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) { } } } } }
From source file:com.clearspring.metriccatcher.MetricCatcher.java
/** * Grab metric messages off the listening socket, creating and updating * them as needed./*from w w w . j av a 2 s. com*/ */ @Override public void run() { // Arbitrary. One metric with a reasonable name is less than 200b // This (http://stackoverflow.com/q/3712151/17339) implies that 64 bit // leenuks will handle packets up to 24,258b, so let's assume we won't // get anything larger than that. Note that this is a hard limit-you // can't accumulate from the socket so anything larger is truncated. byte[] data = new byte[24258]; // Keep track of the last 1000 packets we've seen byte[] json = null; while (shutdown.get() == false) { DatagramPacket received = new DatagramPacket(data, data.length); try { // Pull in network data socket.receive(received); json = received.getData(); if (logger.isDebugEnabled()) { logger.debug("Got packet from " + received.getAddress() + ":" + received.getPort()); if (logger.isTraceEnabled()) { String jsonString = new String(json); logger.trace("JSON: " + jsonString); } } // Turn bytes of JSON into JSONMetric objects TypeReference<List<JSONMetric>> typeRef = new TypeReference<List<JSONMetric>>() { }; List<JSONMetric> jsonMetrics = mapper.readValue(json, typeRef); // Parse all of the metrics in the message for (JSONMetric jsonMetric : jsonMetrics) { if (!metricCache.containsKey(jsonMetric.getName())) { logger.info("Creating new " + jsonMetric.getType().name() + " metric for '" + jsonMetric.getName() + "'"); Metric newMetric = createMetric(jsonMetric); metricCache.put(jsonMetric.getName(), newMetric); } // Record the update logger.debug("Updating " + jsonMetric.getType() + " '" + jsonMetric.getName() + "' with <" + jsonMetric.getValue() + ">"); updateMetric(metricCache.get(jsonMetric.getName()), jsonMetric.getValue()); } } catch (IOException e) { logger.warn("IO error: " + e); String jsonString = new String(json); logger.warn("JSON: " + jsonString); } } socket.close(); }
From source file:org.disrupted.rumble.network.protocols.firechat.workers.FirechatOverUDPMulticast.java
public FirechatOverUDPMulticast(FirechatProtocol protocol, UDPMulticastConnection con) { super(protocol, con); byte[] buffer = new byte[PACKET_SIZE]; this.packet = new DatagramPacket(buffer, PACKET_SIZE); working = false;/* www. j a v a 2 s. c om*/ this.recipientList = new HashSet<Contact>(); }
From source file:org.squidy.manager.protocol.udp.UDPServer.java
@Override public void run() { while (running) { try {/*from ww w . j a v a 2 s.c o m*/ 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 (UDPListener listener : listeners) { listener.parseData(data); } } for (UDPListener listener : listeners) { listener.parseData(packet.getData()); } for (UDPListener listener : listeners) { listener.receive(packet); } } catch (IOException e) { if (LOG.isErrorEnabled()) { LOG.error("Connection error occured."); } } } socket.close(); }
From source file:org.libreoffice.impressremote.communication.TcpServersFinder.java
private DatagramPacket buildSearchPacket() { try {// w w w .j av a 2 s . c o m String aSearchCommand = Protocol.Commands.prepareCommand(Protocol.Commands.SEARCH_SERVERS); DatagramPacket aSearchPacket = new DatagramPacket(aSearchCommand.getBytes(), aSearchCommand.length()); aSearchPacket.setAddress(InetAddress.getByName(Protocol.Addresses.SERVER_SEARCH)); aSearchPacket.setPort(Protocol.Ports.SERVER_SEARCH); return aSearchPacket; } catch (UnknownHostException e) { throw new RuntimeException("Unable to find address to search."); } }
From source file:jlg.jade.test.asterix.cat062.Cat062LargeSampleTest.java
@Test @Ignore("Can only be executed if an Asterix sender is feeding the decoder") public void when_upd_unicast_is_used_as_input_and_datagram_is_large_should_decode_cat062_messages_from_larger_sample() throws IOException { //arrange// ww w . ja v a 2s . com final int PORT = 3001; final int MAX_PACKET_SIZE = 65507; final int TIMEOUT = 20000; //act AsterixDecoder decoder = new AsterixDecoder(62); byte[] networkBuffer = new byte[MAX_PACKET_SIZE]; int receivedDatagrams = 0; int receivedBytes = 0; try (DatagramSocket client = new DatagramSocket(PORT)) { client.setSoTimeout(TIMEOUT); DatagramPacket packet = new DatagramPacket(networkBuffer, networkBuffer.length); while (true) { client.receive(packet); List<AsterixDataBlock> dataBlocks = decoder.decode(networkBuffer, 0, packet.getLength()); for (AsterixDataBlock dataBlock : dataBlocks) { for (AsterixRecord rec : dataBlock.getRecords()) { System.out.println("Decoded new record"); } } //accumulate and print info receivedDatagrams++; receivedBytes += packet.getLength(); if (receivedDatagrams % 100 == 0) { System.out .println("Processed " + receivedDatagrams + " datagrams (" + receivedBytes + ") bytes"); } } } //assert //int expectedDatagrams = 34957; //int expectedBytes = 2306154; //assertEquals(expectedDatagrams, receivedDatagrams); //assertEquals(expectedBytes, receivedBytes); }
From source file:org.rifidi.emulator.io.comm.ip.udp.UDPCommunicationOutgoingMessageHandler.java
/** * The main logic of this monitor. Takes data from the send buffer and sends * it to the client.// www. jav a 2s . com * * @see java.lang.Runnable#run() */ public void run() { /* the packet object to recieve the messages from*/ DatagramPacket pack; /* Should the loop keep running? */ boolean keepRunning = true; /* The data that will be sent */ byte[] data; /* This part loops until we catch an exception */ while (keepRunning) { try { //Take the next packet from the buffer data = host.getSendBuffer().takeNextFromBuffer(); //create a DatagramPacket out of it pack = new DatagramPacket(data, data.length); //Send it over the network newSock.send(pack); } catch (DataBufferInterruptedException e) { //if we catch an exception then the loop stops logger.warn(e.getMessage()); keepRunning = false; } catch (IOException e) { //if we catch an exception then the loop stops logger.warn(e.getMessage()); keepRunning = false; } } }
From source file:org.graylog2.messagehandlers.gelf.GELFTest.java
/** * Test getGELFType method with an invalid encryption *//*from ww w. j av a 2 s. c o m*/ @Test(expected = InvalidGELFCompressionMethodException.class) public void testGetGELFTypeWithInvalidEncryption() throws Exception { // Build a datagram packet. String invalidlyEncryptedString = "mamamamamamamamamamamama"; DatagramPacket invalidGELFMessage = new DatagramPacket(invalidlyEncryptedString.getBytes(), invalidlyEncryptedString.getBytes().length); // Cause the exception we expect. GELF.getGELFType(invalidGELFMessage.getData()); }