List of usage examples for java.net DatagramPacket DatagramPacket
public DatagramPacket(byte buf[], int length, InetAddress address, int port)
From source file:com.cafbit.multicasttest.NetThread.java
/** * Transmit an mDNS query on the local network. * @param host/*w ww .j a v a 2 s. c o m*/ * @throws IOException */ private void query(String host) throws IOException { Log.i(TAG, "query essai 1: " + host); byte[] requestData = (new DNSMessage(host)).serialize(); DatagramPacket request = new DatagramPacket(requestData, requestData.length, InetAddress.getByAddress(MDNS_ADDR), MDNS_PORT); multicastSocket.send(request); }
From source file:com.summit.jbeacon.beacons.MultiCastResourceBeacon.java
/** * refresh the resources that are available. * @throws MultiCastResourceBeaconException if * the data fails to be refreshed/*w ww .ja v a2 s . c o m*/ */ public final void refreshData() throws MultiCastResourceBeaconException { while (!listenerThread.isRunning()) { try { log.debug("Waiting for server to start."); Thread.sleep(threadSleep); } catch (InterruptedException ex) { log.warn("Thread death while waiting for listener to run."); } } log.info("Attempting to refresh data."); if (listeningSocket == null) { throw new MultiCastResourceBeaconException( "Beacon is not " + "listening for responses. Initialize the " + "listener first!"); } MulticastSocket s = null; try { s = new MulticastSocket(); s.setReuseAddress(true); } catch (IOException ex) { throw new MultiCastResourceBeaconException("Error creating multicast socket...", ex); } String broadcastMessage = getBroadcastText() + " : " + getIp() + ":" + getHostName() + ":" + listeningSocket.getLocalPort(); byte[] buf = broadcastMessage.getBytes(); DatagramPacket pack = null; try { log.info("Multicast port: " + getGroupPort()); log.info("Multicast group: " + getGroupAddress()); pack = new DatagramPacket(buf, buf.length, InetAddress.getByName(getGroupAddress()), getGroupPort()); } catch (UnknownHostException ex) { throw new MultiCastResourceBeaconException("Error creating datagram.", ex); } try { s.send(pack); } catch (IOException ex) { throw new MultiCastResourceBeaconException("Error sending message.", ex); } s.close(); }
From source file:org.nebulaframework.discovery.multicast.MulticastDiscovery.java
/** * Responds to a Multicast Discovery Request by publishing * the IP Address of Service into response channel. *///from w w w . j av a 2 s . c o m protected static void doRespond() { // Only allowed for ClusterManagers if (!Grid.isClusterManager()) { throw new UnsupportedOperationException( "Multicast Discovery Service can be enabled only for ClusterManagers"); } try { // Get Broker Service URL String serviceUrl = ClusterManager.getInstance().getClusterInfo().getServiceUrl(); byte[] hostInfo = NetUtils.getHostInfoAsBytes(serviceUrl); // Create Response Packet DatagramPacket response = new DatagramPacket(hostInfo, hostInfo.length, SERVICE_RESPONSE_IP, SERVICE_PORT); // Create Multicast Socket MulticastSocket resSock = new MulticastSocket(); // Send response resSock.send(response); log.debug("[MulticastDiscovery] Responded Discovery Request"); } catch (Exception e) { log.error("[MulticastDiscovery] Service Failed to Reply", e); } }
From source file:com.blueshift.mvpremote.MVPremoteActivity.java
public void onButtonPressed(View v) { byte[] b = new byte[3]; byte val = 0; b[0] = 0x00;// ww w . j a va 2 s .co m switch (v.getId()) { case R.id.bPageUp: val = 11; break; case R.id.bUp: val = 32; break; case R.id.bGreen: val = 46; break; case R.id.bLeft: val = 17; break; case R.id.bOK: val = 37; break; case R.id.bRight: val = 16; break; case R.id.bPageDown: val = 56; break; case R.id.bDown: val = 33; break; case R.id.bBack: val = 41; break; case R.id.bMute: val = 15; break; case R.id.bBlank: val = 12; break; case R.id.bFull: val = 60; break; case R.id.bRewind: val = 50; break; case R.id.bPlay: val = 53; break; case R.id.bFF: val = 52; break; case R.id.bRec: val = 55; break; case R.id.bStop: val = 54; break; case R.id.bPause: val = 48; break; case R.id.b1: val = 1; break; case R.id.b2: val = 2; break; case R.id.b3: val = 3; break; case R.id.b4: val = 4; break; case R.id.b5: val = 5; break; case R.id.b6: val = 6; break; case R.id.b7: val = 7; break; case R.id.b8: val = 8; break; case R.id.b9: val = 9; break; case R.id.b0: val = 0; break; case R.id.bExit: val = 31; break; case R.id.bMenu: val = 13; break; case R.id.Skip: val = 30; break; case R.id.Replay: val = 36; break; } b[1] = (byte) val; if (addr == null) { Toast.makeText(this, "Invalid Host", Toast.LENGTH_LONG).show(); return; } try { s.send(new DatagramPacket(b, 2, addr, 16000)); // b[0] = 0x10; // Thread.sleep(100); // s.send(new DatagramPacket(b,2, addr, 16000)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); } }
From source file:org.motechproject.metrics.impl.StatsdAgentBackendImpl.java
private boolean doSend(DatagramSocket sock, String stat) { if (serverAddr == null) { try {/*w w w . j a v a 2s . c om*/ serverAddr = InetAddress.getByName(serverHost); } catch (UnknownHostException e) { //log.error(e.getMessage()); return false; } } try { byte[] data = stat.getBytes(); sock.send(new DatagramPacket(data, data.length, serverAddr, serverPort)); return true; } catch (IOException e) { //log.error(String.format("Could not send stat %s to host %s:%d", stat, serverHost, serverPort), e); } return false; }
From source file:com.googlecode.jmxtrans.model.output.TCollectorUDPWriter.java
/** * Send a single metric to TCollector./* www. java 2s .c om*/ * * @param metricLine - the line containing the metric name, value, and tags for a single metric; excludes the * "put" keyword expected by OpenTSDB and the trailing newline character. */ @Override protected void sendOutput(String metricLine) throws IOException { DatagramPacket packet; byte[] data; data = metricLine.getBytes("UTF-8"); packet = new DatagramPacket(data, 0, data.length, this.address); this.dgSocket.send(packet); }
From source file:org.rifidi.emulator.reader.alien.heartbeat.HeartbeatController.java
/** * Send out a heartbeat/*w ww. jav a 2s .c o m*/ */ private void broadcast() { String retString = "<Alien-RFID-Reader-Heartbeat>\n" + " <ReaderName>Alien RFID Reader</ReaderName>\n" + " <ReaderType>Alien RFID Tag Reader, Model: ALR-9800(Four Antenna / Multi-Protocol / 915 Mhz)" + "</ReaderType>\n" + " <IPAddress>" + asr.getCommandIP() + "</IPAddress>\n" + " <CommandPort>" + asr.getCommandPort() + "</CommandPort>\n" + " <HeartbeatTime>" + this.timeInMs / 1000 + "</HeartbeatTime>\n" + " <MACAddress>00:00:00:00:00:00</MACAddress>\n" + "</Alien-RFID-Reader-Heartbeat>\n"; try { logger.debug("Attempting to send heartbeat..."); DatagramSocket sock = new DatagramSocket(bindingPort); InetAddress ia = InetAddress.getByName(broadcastAddr); sock.setBroadcast(true); DatagramPacket p = new DatagramPacket(retString.getBytes(), retString.getBytes().length, ia, broadcastPort); sock.send(p); sock.disconnect(); sock.close(); } catch (SocketException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.mule.test.firewall.FirewallTestCase.java
protected void doTestUdp(InetAddress address, int port) throws Exception { try {/* w ww.ja v a 2 s . c om*/ logger.debug("Testing UDP on " + addressToString(address, port)); DatagramSocket server = openUdpServer(address, port); DatagramSocket client = openUdpClient(); client.send(new DatagramPacket(new byte[] { 1 }, 1, address, port)); DatagramPacket packet = new DatagramPacket(new byte[1], 1); server.receive(packet); assertEquals("Failed to send packet via " + addressToString(address, port), 1, packet.getData()[0]); client.close(); server.close(); } catch (Exception e) { logger.error("Error while attempting UDP message on " + addressToString(address, port)); throw e; } }
From source file:com.streamsets.pipeline.stage.origin.udp.TestUDPSource.java
private void doBasicTest(UDPDataFormat dataFormat) throws Exception { List<String> ports = NetworkUtils.getRandomPorts(2); ParserConfig parserConfig = new ParserConfig(); parserConfig.put(CHARSET, "UTF-8"); TUDPSource source = new TUDPSource(ports, parserConfig, dataFormat, 20, 100L); SourceRunner runner = new SourceRunner.Builder(TUDPSource.class, source).addOutputLane("lane").build(); runner.runInit();/* w w w.ja v a 2 s. c om*/ try { byte[] bytes = null; switch (dataFormat) { case NETFLOW: InputStream is = Thread.currentThread().getContextClassLoader() .getResourceAsStream(TEN_PACKETS_RESOURCE); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); is.close(); baos.close(); bytes = baos.toByteArray(); break; case SYSLOG: bytes = "<34>1 2003-10-11T22:14:15.003Z mymachine.example.com some syslog data" .getBytes(StandardCharsets.UTF_8); break; default: Assert.fail("Unknown data format: " + dataFormat); } for (String port : ports) { DatagramSocket clientSocket = new DatagramSocket(); InetAddress address = InetAddress.getLoopbackAddress(); DatagramPacket sendPacket = new DatagramPacket(bytes, bytes.length, address, Integer.parseInt(port)); clientSocket.send(sendPacket); clientSocket.close(); } StageRunner.Output output = runner.runProduce(null, 6); Assert.assertTrue(source.produceCalled); List<Record> records = output.getRecords().get("lane"); switch (dataFormat) { case NETFLOW: Assert.assertEquals(String.valueOf(records), 6, records.size()); break; case SYSLOG: Assert.assertEquals(String.valueOf(records), ports.size(), records.size()); break; default: Assert.fail("Unknown data format: " + dataFormat); } output = runner.runProduce(null, 14); Assert.assertTrue(source.produceCalled); records = output.getRecords().get("lane"); switch (dataFormat) { case NETFLOW: Assert.assertEquals(String.valueOf(records), 14, records.size()); break; case SYSLOG: Assert.assertEquals(String.valueOf(records), 0, records.size()); break; default: Assert.fail("Unknown data format: " + dataFormat); } output = runner.runProduce(null, 1); Assert.assertTrue(source.produceCalled); records = output.getRecords().get("lane"); Assert.assertEquals(String.valueOf(records), 0, records.size()); } finally { runner.runDestroy(); } }
From source file:com.example.android.toyvpn.ToyVpnService.java
private void UDPtoProxy(ByteBuffer packet) throws IOException { //TODO FARE un THREAD?? final DatagramSocket clientSocket = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName("localhost"); //send Pkt to Proxy DatagramPacket sendPacket = new DatagramPacket(packet.array(), packet.array().length, IPAddress, mServerPort);// ww w . j a v a 2 s .com clientSocket.send(sendPacket); }