Receive UDP packets

Hi everyone,

I am currently trying to retrieve UDP packets from an ethernet module connected to my computer. I know that the module is transmitting the UDP packets and my laptop is receiving them (I used Wireshark to confirm it)


However, when trying to run the following processing sketch to receive the UDP packets, I can’t receive them. Am I doing something wrong?

Thanks in advance,

import hypermedia.net.*;
int PORT_RX=8234;
String HOST_IP = "192.168.1.2";//IP Address of the PC in which this App is running
UDP udp;//Create UDP object for receiving

void setup(){
  udp= new UDP(this, PORT_RX, HOST_IP);
  udp.log(true);
  udp.listen(true);
  noLoop();
}

void draw(){
 
} 

void receive(byte[] data, String HOST_IP, int PORT_RX){
 
  String value=new String(data);
  println(value);
    
}

If anyone is looking for an answer, I came with the following code to use as UDP server:

import java.net.*;
import java.io.*;
import java.util.Arrays;

DatagramSocket socket;
DatagramPacket packet;

byte[] buf = new byte[12]; //Set your buffer size as desired

void setup() {
  try {
    socket = new DatagramSocket(5005); // Set your port here
  }
  catch (Exception e) {
    e.printStackTrace(); 
    println(e.getMessage());
  }
}

void draw() {
  try {
    DatagramPacket packet = new DatagramPacket(buf, buf.length);
    socket.receive(packet);
    InetAddress address = packet.getAddress();
    int port = packet.getPort();
    packet = new DatagramPacket(buf, buf.length, address, port);

    //Received as bytes:
    println(Arrays.toString(buf));
    
    //If you wish to receive as String:
    String received = new String(packet.getData(), 0, packet.getLength());
    println(received);
  }
  catch (IOException e) {
    e.printStackTrace(); 
    println(e.getMessage());
  }
}

Hope it helps if someone needs

1 Like