Created
May 8, 2021 23:08
-
-
Save rahji/9d6abc9ca49f1b5e5fa9ef6e1749da34 to your computer and use it in GitHub Desktop.
UDP example for Processing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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