Skip to content

Instantly share code, notes, and snippets.

@rahji
Created May 8, 2021 23:08
Show Gist options
  • Save rahji/9d6abc9ca49f1b5e5fa9ef6e1749da34 to your computer and use it in GitHub Desktop.
Save rahji/9d6abc9ca49f1b5e5fa9ef6e1749da34 to your computer and use it in GitHub Desktop.
UDP example for Processing
import java.net.*;
import java.io.*;
import java.util.Arrays;
// from https://discourse.processing.org/t/receive-udp-packets/19832
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());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment