Java Code Examples for java.net.DatagramPacket#setData()

The following examples show how to use java.net.DatagramPacket#setData() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TesterMulticast.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public void run() {
    try (MulticastSocket s = new MulticastSocket(PORT)) {
        s.setLoopbackMode(false);
        s.joinGroup(INET_ADDRESS);
        DatagramPacket p = new DatagramPacket(new byte[4], 4);
        p.setAddress(INET_ADDRESS);
        p.setPort(PORT);
        long counter = 0;
        String msg;
        while (run) {
            msg = String.format("%04d", Long.valueOf(counter));
            p.setData(msg.getBytes());
            System.out.println("Tx: " + msg);
            s.send(p);
            counter++;
            Thread.sleep(500);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 2
Source File: UDPConnector.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void sendMessage(final IAgent sender, final String receiver, final String cont)
		throws GamaNetworkException {
	String content = cont.replaceAll("\b\r", "@b@@r@");
	content = content.replaceAll("\n", "@n@");

	final String sport = this.getConfigurationParameter(SERVER_PORT);
	final Integer port = Cast.asInt(sender.getScope(), sport);

	try (final DatagramSocket clientSocket = new DatagramSocket();) {
		final InetAddress IPAddress = InetAddress.getByName((String) sender.getAttribute(INetworkSkill.SERVER_URL));
		final byte[] sendData = content.getBytes();
		final DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
		sendPacket.setData(sendData);
		clientSocket.send(sendPacket);
	} catch (final Exception e) {
		e.printStackTrace();
	}

}
 
Example 3
Source File: Offset.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {

        byte b1[] = new byte[1024];
        DatagramPacket p = new DatagramPacket(b1, 512, 512 );

        byte b2[] = new byte[20];
        p.setData(b2);

        if (p.getOffset() != 0) {
            throw new Exception("setData(byte[]) didn't reset offset");
        }
    }
 
Example 4
Source File: TimelyUdpIT.java    From timely with Apache License 2.0 5 votes vote down vote up
@Test
public void testPut() throws Exception {
    final TestServer m = new TestServer(conf);
    m.run();
    InetSocketAddress address = new InetSocketAddress("127.0.0.1", 54325);
    DatagramPacket packet = new DatagramPacket("".getBytes(UTF_8), 0, 0, address.getAddress(), 54325);
    try (DatagramSocket sock = new DatagramSocket()) {
        // @formatter:off
        packet.setData(("put sys.cpu.user " + TEST_TIME + " 1.0 tag1=value1 tag2=value2\n").getBytes(UTF_8));
        sock.send(packet);
        while (1 != m.getUdpRequests().getCount()) {
            Thread.sleep(5);
        }
        Assert.assertEquals(1, m.getUdpRequests().getResponses().size());
        Assert.assertEquals(MetricRequest.class, m.getUdpRequests().getResponses().get(0).getClass());
        final MetricRequest actual = (MetricRequest) m.getUdpRequests().getResponses().get(0);
        final MetricRequest expected = new MetricRequest(
                Metric.newBuilder()
                        .name("sys.cpu.user")
                        .value(TEST_TIME, 1.0D)
                        .tag(new Tag("tag1", "value1"))
                        .tag(new Tag("tag2", "value2"))
                        .build()
        );
        Assert.assertEquals(expected, actual);
        // @formatter:on
    } finally {
        m.shutdown();
    }
}
 
Example 5
Source File: Offset.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {

        byte b1[] = new byte[1024];
        DatagramPacket p = new DatagramPacket(b1, 512, 512 );

        byte b2[] = new byte[20];
        p.setData(b2);

        if (p.getOffset() != 0) {
            throw new Exception("setData(byte[]) didn't reset offset");
        }
    }
 
Example 6
Source File: Offset.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {

        byte b1[] = new byte[1024];
        DatagramPacket p = new DatagramPacket(b1, 512, 512 );

        byte b2[] = new byte[20];
        p.setData(b2);

        if (p.getOffset() != 0) {
            throw new Exception("setData(byte[]) didn't reset offset");
        }
    }
 
Example 7
Source File: TimelyUdpIT.java    From timely with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutInvalidTimestamp() throws Exception {
    final TestServer m = new TestServer(conf);
    m.run();
    InetSocketAddress address = new InetSocketAddress("127.0.0.1", 54325);
    DatagramPacket packet = new DatagramPacket("".getBytes(UTF_8), 0, 0, address.getAddress(), 54325);
    try (DatagramSocket sock = new DatagramSocket();) {
        packet.setData(("put sys.cpu.user " + TEST_TIME + "Z" + " 1.0 tag1=value1 tag2=value2\n").getBytes(UTF_8));
        sock.send(packet);
        sleepUninterruptibly(TestConfiguration.WAIT_SECONDS, TimeUnit.SECONDS);
        Assert.assertEquals(0, m.getUdpRequests().getCount());
    } finally {
        m.shutdown();
    }
}
 
Example 8
Source File: Offset.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {

        byte b1[] = new byte[1024];
        DatagramPacket p = new DatagramPacket(b1, 512, 512 );

        byte b2[] = new byte[20];
        p.setData(b2);

        if (p.getOffset() != 0) {
            throw new Exception("setData(byte[]) didn't reset offset");
        }
    }
 
Example 9
Source File: Offset.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {

        byte b1[] = new byte[1024];
        DatagramPacket p = new DatagramPacket(b1, 512, 512 );

        byte b2[] = new byte[20];
        p.setData(b2);

        if (p.getOffset() != 0) {
            throw new Exception("setData(byte[]) didn't reset offset");
        }
    }
 
Example 10
Source File: Offset.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {

        byte b1[] = new byte[1024];
        DatagramPacket p = new DatagramPacket(b1, 512, 512 );

        byte b2[] = new byte[20];
        p.setData(b2);

        if (p.getOffset() != 0) {
            throw new Exception("setData(byte[]) didn't reset offset");
        }
    }
 
Example 11
Source File: UDPEmitter.java    From aws-xray-sdk-java with Apache License 2.0 5 votes vote down vote up
private boolean sendData(byte[] data, Entity entity) {
    try {
        DatagramPacket packet = new DatagramPacket(sendBuffer, DAEMON_BUF_RECEIVE_SIZE, config.getAddressForEmitter());
        packet.setData(data);
        logger.debug("Sending UDP packet.");
        daemonSocket.send(packet);
    } catch (Exception e) {
        String segmentName = Optional.ofNullable(entity.getParent()).map(this::nameAndId).orElse("[no parent segment]");
        logger.error("Exception while sending segment over UDP for entity " +  nameAndId(entity) + " on segment "
                     + segmentName, e);
        return false;
    }
    return true;
}
 
Example 12
Source File: UDPMetricEmitter.java    From aws-xray-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void emitMetric(final Segment segment) {
    String formattedMetric = formatter.formatSegment(segment);
    DatagramPacket packet = new DatagramPacket(sendBuffer, BUFFER_SIZE, address);
    packet.setData(formattedMetric.getBytes(StandardCharsets.UTF_8));
    try {
        socket.send(packet);
    } catch (IOException e) {
        logger.error("Unable to send metric to agent.", e);
    }
}
 
Example 13
Source File: RUDPServer.java    From jRUDP with MIT License 5 votes vote down vote up
protected void sendPacket(byte[] data, InetAddress address, int port){
	DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
       packet.setData(data);
       try {
		datagramSocket.send(packet);
	} catch (IOException e) {e.printStackTrace();}
}
 
Example 14
Source File: VDatagramSocket.java    From finalspeed with GNU General Public License v2.0 5 votes vote down vote up
public synchronized void receive(DatagramPacket p) throws IOException {
    TunData td;
    try {
        td = packetList.take();
        p.setData(td.data);
        p.setLength(td.data.length);
        p.setAddress(td.tun.remoteAddress);
        p.setPort(CapEnv.toUnsigned(td.tun.remotePort));
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
 
Example 15
Source File: Offset.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {

        byte b1[] = new byte[1024];
        DatagramPacket p = new DatagramPacket(b1, 512, 512 );

        byte b2[] = new byte[20];
        p.setData(b2);

        if (p.getOffset() != 0) {
            throw new Exception("setData(byte[]) didn't reset offset");
        }
    }
 
Example 16
Source File: Offset.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {

        byte b1[] = new byte[1024];
        DatagramPacket p = new DatagramPacket(b1, 512, 512 );

        byte b2[] = new byte[20];
        p.setData(b2);

        if (p.getOffset() != 0) {
            throw new Exception("setData(byte[]) didn't reset offset");
        }
    }
 
Example 17
Source File: SocketManagerTest.java    From mts with GNU General Public License v3.0 4 votes vote down vote up
/**
   * @param args
   */
  public static void main(String[] args) throws Exception {
  	
      host = Utils.getLocalAddress().getHostAddress();
      port = 10000;
  	transport = "udp";

  	InetSocketAddress localDatagramSocketAddress = new InetSocketAddress(host, port);
  	DatagramSocket datagramSocket = new DatagramSocket(localDatagramSocketAddress);
  	
  	String packet = createRequest(0);
  	byte[] data = Utils.parseBinaryString(packet);
      System.out.println("length = " + data.length);

DatagramPacket dp = new DatagramPacket(data, data.length);
      InetSocketAddress remoteDatagramSocketAddress = new InetSocketAddress(host, port);
      dp.setSocketAddress(remoteDatagramSocketAddress);

      int maxIter = 100000;
      System.out.println("maxIter : " + maxIter);
      
      long beginTT = new GregorianCalendar().getTimeInMillis();
      for (int i = 1; i <= maxIter; i++) {
          // Create a message object corresponding to the string message
          if (i % 1000 == 0) {
              // System.out.println("i=" + i);
          }
          
          // MsgUdp msg = new MsgUdp(data, data.length);
          // msg.setListenpoint(listenpoint);
          
  		dp.setData(data);
          // remoteDatagramSocketAddress = new InetSocketAddress(host, port);
          dp.setSocketAddress(remoteDatagramSocketAddress);
  		
	datagramSocket.send(dp);            
      }
      long endTT = new GregorianCalendar().getTimeInMillis();
      float duration = ((float)(endTT - beginTT)) / 1000;
      float flow = maxIter / duration;
      System.out.println("nombre trans = " + maxIter + " msg.");
      System.out.println("duration = " + duration + " s.");
      System.out.println("msg flow = " + flow + " msg/s.");

      System.out.println("Hit enter to terminate server");
      System.in.read();

  }
 
Example 18
Source File: EKeyPacketReceiver.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void run() {
    running = true; // start loop
    if (socket == null) {
        throw new IllegalStateException(
                "Cannot access socket. You must call" + " call initializeListener(..) first!");
    }

    byte[] lastpacket = null;
    DatagramPacket packet = new DatagramPacket(new byte[buffersize], buffersize);

    while (running) {

        ekeypacket = null;
        packet.setData(new byte[buffersize]);

        try { // wait for the packet
            socket.receive(packet);
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        // ignore packets from destinations other than the specified address
        // if destIp is not set ignore address check - this is not recommended but valid
        if (destIp == null || packet.getAddress().equals(destIp)) {

            lastpacket = packet.getData();

            try { // catch a possible parsing error

                switch (mode) {
                    case UniformPacket.tHOME:
                        ekeypacket = new HomePacket(deliminator, lastpacket);
                        break;
                    case UniformPacket.tMULTI:
                        ekeypacket = new MultiPacket(deliminator, lastpacket);
                        break;
                    default: // default configuration is the rare packet
                        ekeypacket = new RarePacket(lastpacket);
                        break;

                }
            } catch (IllegalArgumentException e) {
                log.error("Error parsing packet", e);
            }
        }

        if (ekeypacket != null) {
            listener.publishUpdate(ekeypacket);
        } else {
            log.debug("Received a packet that does not match the mode\n" + "you specified in the 'openhab.cfg'!");
        }

    }

    log.debug("eKey Listener stopped!");

}
 
Example 19
Source File: TimelyUdpIT.java    From timely with Apache License 2.0 4 votes vote down vote up
@Test
public void testPutMultiple() throws Exception {

    final TestServer m = new TestServer(conf);
    m.run();
    InetSocketAddress address = new InetSocketAddress("127.0.0.1", 54325);
    DatagramPacket packet = new DatagramPacket("".getBytes(UTF_8), 0, 0, address.getAddress(), 54325);
    // @formatter:off
    try (DatagramSocket sock = new DatagramSocket()) {
        packet.setData(("put sys.cpu.user " + TEST_TIME + " 1.0 tag1=value1 tag2=value2\n"
                      + "put sys.cpu.idle " + (TEST_TIME + 1) + " 1.0 tag3=value3 tag4=value4\n").getBytes(UTF_8));
        sock.send(packet);
        while (2 != m.getUdpRequests().getCount()) {
            Thread.sleep(5);
        }
        Assert.assertEquals(2, m.getUdpRequests().getResponses().size());
        Assert.assertEquals(MetricRequest.class, m.getUdpRequests().getResponses().get(0).getClass());
        MetricRequest actual = (MetricRequest) m.getUdpRequests().getResponses().get(0);
        MetricRequest expected = new MetricRequest (
                Metric.newBuilder()
                        .name("sys.cpu.user")
                        .value(TEST_TIME, 1.0D)
                        .tag(new Tag("tag1", "value1"))
                        .tag(new Tag("tag2", "value2"))
                        .build()
        );
        Assert.assertEquals(expected, actual);

        Assert.assertEquals(MetricRequest.class, m.getUdpRequests().getResponses().get(1).getClass());
        actual = (MetricRequest) m.getUdpRequests().getResponses().get(1);
        expected = new MetricRequest(
                Metric.newBuilder()
                        .name("sys.cpu.idle")
                        .value(TEST_TIME + 1, 1.0D)
                        .tag(new Tag("tag3", "value3"))
                        .tag(new Tag("tag4", "value4"))
                        .build()
        );
        Assert.assertEquals(expected, actual);
        // @formatter:on
    } finally {
        m.shutdown();
    }
}
 
Example 20
Source File: TimelyUdpIT.java    From timely with Apache License 2.0 4 votes vote down vote up
@Test
public void testPutMultipleBinary() throws Exception {

    FlatBufferBuilder builder = new FlatBufferBuilder(1);

    int[] metric = new int[2];
    Map<String, String> t = new HashMap<>();
    t.put("tag1", "value1");
    t.put("tag2", "value2");
    metric[0] = createMetric(builder, "sys.cpu.user", TEST_TIME, 1.0D, t);
    t = new HashMap<>();
    t.put("tag3", "value3");
    t.put("tag4", "value4");
    metric[1] = createMetric(builder, "sys.cpu.idle", TEST_TIME + 1, 1.0D, t);

    int metricVector = timely.api.flatbuffer.Metrics.createMetricsVector(builder, metric);

    timely.api.flatbuffer.Metrics.startMetrics(builder);
    timely.api.flatbuffer.Metrics.addMetrics(builder, metricVector);
    int metrics = timely.api.flatbuffer.Metrics.endMetrics(builder);
    timely.api.flatbuffer.Metrics.finishMetricsBuffer(builder, metrics);

    ByteBuffer binary = builder.dataBuffer();
    byte[] data = new byte[binary.remaining()];
    binary.get(data, 0, binary.remaining());
    LOG.debug("Sending {} bytes", data.length);

    final TestServer m = new TestServer(conf);
    m.run();
    InetSocketAddress address = new InetSocketAddress("127.0.0.1", 54325);
    DatagramPacket packet = new DatagramPacket("".getBytes(UTF_8), 0, 0, address.getAddress(), 54325);
    try (DatagramSocket sock = new DatagramSocket()) {
        packet.setData(data);
        sock.send(packet);
        while (2 != m.getUdpRequests().getCount()) {
            Thread.sleep(5);
        }
        Assert.assertEquals(2, m.getUdpRequests().getResponses().size());
        Assert.assertEquals(MetricRequest.class, m.getUdpRequests().getResponses().get(0).getClass());
        // @formatter:off
        MetricRequest actual = (MetricRequest) m.getUdpRequests().getResponses().get(0);
        MetricRequest expected = new MetricRequest(
                Metric.newBuilder()
                        .name("sys.cpu.user")
                        .value(TEST_TIME, 1.0D)
                        .tag(new Tag("tag1", "value1"))
                        .tag(new Tag("tag2", "value2"))
                        .build()
        );
        Assert.assertEquals(expected, actual);

        Assert.assertEquals(MetricRequest.class, m.getUdpRequests().getResponses().get(1).getClass());
        actual = (MetricRequest) m.getUdpRequests().getResponses().get(1);
        expected = new MetricRequest(
                Metric.newBuilder()
                        .name("sys.cpu.idle")
                        .value(TEST_TIME + 1, 1.0D)
                        .tag(new Tag("tag3", "value3"))
                        .tag(new Tag("tag4", "value4"))
                        .build()
        );
        Assert.assertEquals(expected, actual);
        // @formatter:on

    } finally {
        m.shutdown();
    }
}